Shell – portably assign value to dynamically named shell variable

shell

The Almquist shell on Slackware 14.2, but not Debian's Almquist shell, supports the following construction. Other Bourne-like shells do not.

setvar "$varname" <...>

Bash evidently has the ability to dynamically create variable names

declare "magic_variable_$1=$(ls | tail -1)"

I think there are some restrictions on the characters that can appear in $1 though… (= comes to mind).

This is suggested as a workaround for faking associative arrays in pre-4.0 Bashes.

I can come up with a silly function for assigning to a dynamically created variable off the top of my head using eval.

NOTE: DO NOT USE THIS FUNCTION FOR ANY REASON, IT'S TOTALLY INSECURE.

assign_dynamically() {
    eval "$1='$2'"
}

This thing chokes if the value $2 contains ' and doesn't support whitespace or metacharacters in $1, however, so it isn't a solution.

Is there a portable/POSIX-compatible way to write a function that assigns $2 into a variable named $1 regardless of the contents of either string?

Best Answer

Regardless of either string, no. the first parameter needs to be a valid variable name.

dynamic_assign(){ eval "$1"=\"\$2\" ; }

is about as good as you are going to get

Related Question