How to assign to a variable whose name is stored in another variable in bash? Something like (the example does not work):
foo=1
a='foo'
$a=42 # This does not work:"bash: foo=42: command not found"
# Want foo == 42 here
You want:
eval "$a=42"
For example:
$ a=foo
$ eval "$a=42"
$ echo $foo
42
eval is dangerous. If a='date; foo' then it will execute date command before assigning 42 to foo. Now imagine if date is replaced by some rm command.eval is dangerous - you have to be able to trust where a comes from (among other things); this may be OK if it is guaranteed to come from your own script. Unfortunately declare is not available in all shells, though the question is about bash so it can be used here.You can use eval. For example:
var1=abc
eval $var1="value1" # abc set to value1