Thursday, June 25, 2009

Bash Tricks - Variable variable name

There are rare situations where you will have to use the value of a variable as another variable name, bash provides a special construct for this purpose.

Create a variable and assign a value

safeer@penguin-power:~/temp$ MY_VAR1="MY_VALUE1"

Assign the variable name "MY_VAR1" to MY_VAR2.

safeer@penguin-power:~/temp$ MY_VAR2="MY_VAR1"

Now use MY_VAR2 to print the contents of MY_VAR1

safeer@penguin-power:~/temp$ echo ${!MY_VAR2}
MY_VALUE1

Let us try with an example where command line arguments ( $1,$2,$3 etc.... ) of a script are parsed using the argument numbers (1,2,3...) taken from another variable.

safeer@penguin-power:~/temp$ cat test.sh
#!/bin/bash
for((i=1;i<=$#;i++))
do
echo ${!i};
done

safeer@penguin-power:~/temp$ ./test.sh first second third fourth
first
second
third
fourth

safeer@penguin-power:~/temp$ ./test.sh first
first

No comments:

Post a Comment