Following on indirection when getting the value of a variable…
The portable way is to use eval
. You do have to pay attention to the quoting so that special characters in the value are not evaluated when they shouldn't be. The easiest way is to store the new value in an intermediate variable and assign the value of that variable.
A=B
tmp='stuff with special characters or whatever…'
eval $A=\$tmp
The argument to eval
is B=$tmp
, a straightforward assignment. You don't need double quotes around $tmp
even if it contains whitespace or globbing characters, because those are not expanded in an assignment.
If you want to make an environment variable, you can use export
. In bash or ksh or zsh, you can use typeset
to make a local variable (declare
is synonymous in bash). Again, you should use an intermediate variable so that special characters are not mangled. Note that except in zsh, you need to put double quotes around the variable expansion, because this is not an assignment but a builtin that takes an argument that happens to look like an assignment.
export $A="$tmp"
eval $A=foobar
– forcefsck Mar 18 '13 at 16:32