Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to build variable names from other variables in bash? [duplicate]

Tags:

variables

bash

I apologise for the pretty terrible title - and the poor quality post - but what I basically want to do is this:

for I in 1 2 3 4     echo $VAR$I # echo the contents of $VAR1, $VAR2, $VAR3, etc. 

Obviously the above does not work - it will (I think) try and echo the variable called $VAR$I Is this possible in Bash?

like image 405
Stephen Avatar asked Oct 18 '10 21:10

Stephen


People also ask

How do I create a dynamic variable in bash?

You can simply store the name of the variable in an indirection variable, not unlike a C pointer. Bash then has a syntax for reading the aliased variable: ${! name} expands to the value of the variable whose name is the value of the variable name . You can think of it as a two-stage expansion: ${!

Can you name a variable with another variable?

No, you can't, and it makes no sense honestly to have a feature like that. Show activity on this post. No, and it doesn't make any sense. Variable (or more precisely, local) names are only important at compile-time, and they only have values at runtime.

Can you reuse variable names in different functions?

Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes.

Can you name Double variables?

Variable name may not start with a digit or underscore, and may not end with an underscore. Double underscores are not permitted in variable name. Variable names may not be longer than 32 characters and are required to be shorter for some question types: multiselect, GPS location and some other question types.


2 Answers

Yes, but don't do that. Use an array instead.

If you still insist on doing it that way...

$ foo1=123 $ bar=foo1 $ echo "${!bar}" 123 
like image 169
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 12:10

Ignacio Vazquez-Abrams


for I in 1 2 3 4 5; do     TMP="VAR$I"     echo ${!TMP} done 

I have a general rule that if I need indirect access to variables (ditto arrays), then it is time to convert the script from shell into Perl/Python/etc. Advanced coding in shell though possible quickly becomes a mess.

like image 33
Dummy00001 Avatar answered Oct 18 '22 13:10

Dummy00001