pseudomarvin
pseudomarvin

Reputation: 1627

Assign to a variable whose name is stored in another variable in bash

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

Upvotes: 1

Views: 84

Answers (3)

Mahdi
Mahdi

Reputation: 714

You can use eval. For example:

var1=abc

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

Upvotes: 1

anubhava
anubhava

Reputation: 785058

Use declare directive:

declare -- $a=42

Check content of foo:

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

echo "$foo"
42

Upvotes: 2

psmears
psmears

Reputation: 28000

You want:

eval "$a=42"

For example:

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

Upvotes: 1

Related Questions