1

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

3 Answers 3

2

Use declare directive:

declare -- $a=42

Check content of foo:

declare -p foo
declare -- foo="42"

echo "$foo"
42
Sign up to request clarification or add additional context in comments.

Comments

1

You want:

eval "$a=42"

For example:

$ a=foo
$ eval "$a=42"
$ echo $foo
42

2 Comments

Using 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.
@anubhava: Yes, 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.
1

You can use eval. For example:

var1=abc

eval $var1="value1"   # abc set to value1

1 Comment

Why is this upvoted more than the excepted answer. It was created after

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.