Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 292
Haiyuan Zhang Avatar asked Mar 15 '12 06:03

Haiyuan Zhang


People also ask

What is $@ in bash?

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.

How do you variable A variable in bash?

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.


2 Answers

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

like image 63
Kaz Avatar answered Sep 23 '22 12:09

Kaz


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 
like image 39
Flimm Avatar answered Sep 22 '22 12:09

Flimm