How to use a variable’s value as another variable’s name in bash [duplicate]

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:

name_of_variable=abc

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.)

Leave a Comment