Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable to refer to another variable in Bash

Tags:

x=1 c1=string1 c2=string2 c3=string3  echo $c1 string1 

I'd like to have the output be string1 by using something like: echo $(c($x))

So later in the script I can increment the value of x and have it output string1, then string2 and string3.

Can anyone point me in the right direction?

like image 285
user316100 Avatar asked Apr 14 '10 02:04

user316100


People also ask

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.

How do you reference a variable in shell script?

So, first rule: always quote your variables. You can use either "$foo" or "${foo}" but quote it either way. For more detail on using variables safely, have a look at these posts: $VAR vs ${VAR} and to quote or not to quote.

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.


Video Answer


2 Answers

See the Bash FAQ: How can I use variable variables (indirect variables, pointers, references) or associative arrays?

To quote their example:

realvariable=contents ref=realvariable echo "${!ref}"   # prints the contents of the real variable 

To show how this is useful for your example:

get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; } x=1 c1=string1 c2=string2 c3=string3 echo "$(get_c)" 

If, of course, you want to do it the Right Way and just use an array:

c=( "string1" "string2" "string3" ) x=1 echo "${c[$x]}" 

Note that these arrays are zero-indexed, so with x=1 it prints string2; if you want string1, you'll need x=0.

like image 137
Charles Duffy Avatar answered Sep 23 '22 01:09

Charles Duffy


Try this:

eval echo \$c$x 

Like others said, it makes more sense to use array in this case.

like image 33
Hai Vu Avatar answered Sep 26 '22 01:09

Hai Vu