bash: variable variables

2008-12-05 Fri – 21:54:12

How to use variable variables in bash:

[mimi:pgl]:~ $ tits=arse
[mimi:pgl]:~ $ arse=cheese
 
# this way I figured out myself after a long time pulling my hair out
[mimi:pgl]:~ $ echo ${!tits}
cheese
 
# this I found later at http://www.seocam.net/how-tos/how-to-create-variable-variables-in-bash
[mimi:pgl]:~ $ eval echo $`echo $tits`
cheese
 
# how to assign to a variable variable:
[vini:plowe]:~ $ tits=cheese
[vini:plowe]:~ $ arse=tits
[vini:plowe]:~ $ eval $arse='hello'
[vini:plowe]:~ $ echo $tits
hello

Explained — obliquely — in the manual:

   Parameter Expansion

   ...

       If the first character of parameter is an exclamation point, a level of
       variable indirection is introduced.  Bash uses the value of  the  vari-
       able  formed  from  the  rest of parameter as the name of the variable;
       this variable is then expanded and that value is used in  the  rest  of
       the  substitution,  rather than the value of parameter itself.  This is
       known as indirect expansion.  The exceptions to this are the expansions
       of  ${!prefix*} and ${!name[@]} described below.  The exclamation point
       must immediately follow the left brace in order to  introduce  indirec-
       tion.

(“This is known as indirect expansion” – rubbish! Everyone calls it variable
variables! :))

  1. 6 Responses to “bash: variable variables”

  2. nice work balls, this is bangin!

    By manky.turd on Aug 12, 2010

  3. Wow… you’re among top google results and you just saved me hours of work… thanks, great post!

    By Jni on Nov 8, 2010

  4. Actually, this is a bit out of date, and version of bash since version 3 (eg, after about Fedora 8 I think) can do this:

    #!/bin/bash

    foo=wibble
    wibble=works

    echo $foo
    echo ${!foo}

    Curly braces and an exclamation mark is a lot more intuitive than the old eval $$ stuff.

    By Rob Thomas on Jun 19, 2011

  5. That’s right Rob – that’s the first example I put at the top of the post. The others are just for completeness really.

    By pgl on Jun 19, 2011

  6. When scripting for dash you don’t have the ${!var} option, so you must use the “eval echo” trick.

    I have come with a simplified version of yours, omitting an “echo”:

    eval echo \$$tits

    or, to set a variable:

    value=`eval echo \$$tits`

    By xOneca on Jan 18, 2012

  7. This was extremely helpful, thanks so much!

    By anon on May 4, 2012

Sorry, comments for this entry are closed at this time.