• Uncategorized

About bash : How-to-use-a-variables-value-as-another-variables-name-in-bash-duplicate

Question Detail

I want to declare a variable, the name of which comes from the value of another variable, and I wrote the following piece of code:


but it didn’t work. What’s the right way to get this job done?

Question Answer

eval is used for this, but if you do it naively, there are going to be nasty escaping issues. This sort of thing is generally safe:


eval $name_of_variable="simpleword"   # abc set to simpleword

This breaks:

eval $name_of_variable="word splitting occurs"

The fix:

eval $name_of_variable="\"word splitting occurs\""  # not anymore

The ultimate fix: put the text you want to assign into a variable. Let’s call it safevariable. Then you can do this:

eval $name_of_variable=\$safevariable  # note escaped dollar sign

Escaping the dollar sign solves all escape issues. The dollar sign survives verbatim into the eval function, which will effectively perform this:

eval 'abc=$safevariable' # dollar sign now comes to life inside eval!

And of course this assignment is immune to everything. safevariable can contain *, spaces, $, etc. (The caveat being that we’re assuming name_of_variable contains nothing but a valid variable name, and one we are free to use: not something special.)

You can use declare and !, like this:

John="nice guy"
echo ${!programmer} # echos nice guy

Second example:

declare $programmer="nice gal"
echo $Ines # echos nice gal

This might work for you:

declare $foo=baz
echo $bar

or this:

read $foo <<<"baz"
echo $bar

You could make use of eval for this.

$ a="bbb"
$ eval $a="ccc"
$ echo $bbb

Hope this helps!

If you want to get the value of the variable instead of setting it you can do this

eval temp_var=\$$var_name1
echo "$temp_var"

You can read about it here indirect references.

You can assign a value to a variable using simple assignment using a value from another variable like so:


#variable one

echo "Variable a is $a"
#variable two with a's variable

echo "Variable b is $b"

#change a
echo "Variable a is $a"
echo "Variable b is $b"

The output of that is this:

Variable a is one
Variable b is one
Variable a is two
Variable b is one

So just be sure to assign it like this b=”$a” and you should be good.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.