This question already has an answer here:
- Dynamic variable names in Bash 10 answers
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:
a="bbb"
$a="ccc"
but it didn't work. What's the right way to get this job done?
You can assign a value to a variable using simple assignment using a value from another variable like so:
The output of that is this:
So just be sure to assign it like this b="$a" and you should be good.
If you want to get the value of the variable instead of setting it you can do this
You can read about it here indirect references.
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:This breaks:
The fix:
The ultimate fix: put the text you want to assign into a variable. Let's call it
safevariable
. Then you can do this:Escaping the dollar sign solves all escape issues. The dollar sign survives verbatim into the
eval
function, which will effectively perform this:And of course this assignment is immune to everything.
safevariable
can contain*
, spaces,$
, etc. (The caveat being that we're assumingname_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:Second example:
This might work for you:
or this:
You could make use of
eval
for this.Example:
Hope this helps!