Archive

Posts Tagged ‘bash’

Call a variable whose name is contained by another one [BASH]

November 4, 2013 No comments

numbers

I’m sure this has happened to you. Imagine we have three variables (RED = “ff0000″ ; GREEN = “00ff00″ ; BLUE = “0000ff”) and a function which giving the name of the color, it gives us the code. Ok, we can do this many ways, but this is just an example. What I want is to tell get_color() function a name of a variable, and it will give me the value:

1
2
3
4
5
6
7
8
9
10
RED="ff0000"
GREEN="00ff00"
BLUE="0000ff"

function get_color()
{
   echo ${!1}
}

get_color BLUE

The key, as you may see is the ! sign before the name of the variable in braces. It can be a bit more clearer:

1
2
3
4
5
6
7
SEVILLE="Torre del Oro"
LONDON="Big Ben"
NEWYORK="Statue of Liberty"

CITY=SEVILLE

echo I really like to go to $CITY to see ${!CITY}

If I change the value of CITY, it will pick another monument from the list before.

Top