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! :))

Tags: , , , ,

  1. One Response to “bash: variable variables”

  2. nice work balls, this is bangin!

    By manky.turd on Aug 12, 2010

Post a Comment