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?
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.
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.)
You can use declare
and !
, like this:
John="nice guy" programmer=John echo ${!programmer} # echos nice guy
Second example:
programmer=Ines declare $programmer="nice gal" echo $Ines # echos nice gal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With