9.5. Indirect References

We have seen that referencing a variable, $var, fetches its value. But, what about the value of a value? What about $$var?

The actual notation is \$$var, usually preceded by an eval (and sometimes an echo). This is called an indirect reference.


Example 9-24. Indirect Variable References

   1 #!/bin/bash
   2 # ind-ref.sh: Indirect variable referencing.
   3 # Accessing the contents of the contents of a variable.
   4 
   5 # First, let's fool around a little.
   6 
   7 var=23
   8 
   9 echo "\$var   = $var"           # $var   = 23
  10 # So far, everything as expected. But ...
  11 
  12 echo "\$\$var  = $$var"         # $$var  = 4570var
  13 # Not meaningful. The contents of a memory location pointed to?
  14 # Not useful at this point.
  15 
  16 echo "\\\$\$var = \$$var"       # \$$var = $23
  17 #  As expected. The first $ is escaped and pasted on to
  18 #+ the value of var ($var = 23 ).
  19 #  Meaningful, but still not useful. 
  20 
  21 # Now, let's start over and do it the right way.
  22 
  23 # ============================================== #
  24 
  25 
  26 a=letter_of_alphabet   # Variable "a" holds the name of another variable.
  27 letter_of_alphabet=z
  28 
  29 echo
  30 
  31 # Direct reference.
  32 echo "a = $a"          # a = letter_of_alphabet
  33 
  34 # Indirect reference.
  35   eval a=\$$a
  36 # ^^^        Forcing an eval(uation), and ...
  37 #        ^   Escaping the first $ ...
  38 # ------------------------------------------------------------------------
  39 # The 'eval' forces an update of $a, sets it to the updated value of \$$a.
  40 # So, we see why 'eval' so often shows up in indirect reference notation.
  41 # ------------------------------------------------------------------------
  42   echo "Now a = $a"    # Now a = z
  43 
  44 echo
  45 
  46 
  47 # Now, let's try changing the second-order reference.
  48 
  49 t=table_cell_3
  50 table_cell_3=24
  51 echo "\"table_cell_3\" = $table_cell_3"            # "table_cell_3" = 24
  52 echo -n "dereferenced \"t\" = "; eval echo \$$t    # dereferenced "t" = 24
  53 # In this simple case, the following also works (why?).
  54 #         eval t=\$$t; echo "\"t\" = $t"
  55 
  56 echo
  57 
  58 t=table_cell_3
  59 NEW_VAL=387
  60 table_cell_3=$NEW_VAL
  61 echo "Changing value of \"table_cell_3\" to $NEW_VAL."
  62 echo "\"table_cell_3\" now $table_cell_3"
  63 echo -n "dereferenced \"t\" now "; eval echo \$$t
  64 # "eval" takes the two arguments "echo" and "\$$t" (set equal to $table_cell_3)
  65 
  66 
  67 echo
  68 
  69 # (Thanks, Stephane Chazelas, for clearing up the above behavior.)
  70 
  71 
  72 # Another method is the ${!t} notation, discussed in "Bash, version 2" section.
  73 # See also ex78.sh.
  74 
  75 exit 0

Of what practical use is indirect referencing of variables? It gives Bash a little of the functionality of pointers in C, for instance, in table lookup. And, it also has some other very interesting applications. . . .

Nils Radtke shows how to build "dynamic" variable names and evaluate their contents. This can be useful when sourcing configuration files.

   1 #!/bin/bash
   2 
   3 
   4 # ---------------------------------------------
   5 # This could be "sourced" from a separate file.
   6 isdnMyProviderRemoteNet=172.16.0.100
   7 isdnYourProviderRemoteNet=10.0.0.10
   8 isdnOnlineService="MyProvider"
   9 # ---------------------------------------------
  10       
  11 
  12 remoteNet=$(eval "echo \$$(echo isdn${isdnOnlineService}RemoteNet)")
  13 remoteNet=$(eval "echo \$$(echo isdnMyProviderRemoteNet)")
  14 remoteNet=$(eval "echo \$isdnMyProviderRemoteNet")
  15 remoteNet=$(eval "echo $isdnMyProviderRemoteNet")
  16 
  17 echo "$remoteNet"    # 172.16.0.100
  18 
  19 # ================================================================
  20 
  21 #  And, it gets even better.
  22 
  23 #  Consider the following snippet given a variable named getSparc,
  24 #+ but no such variable getIa64:
  25 
  26 chkMirrorArchs () { 
  27   arch="$1";
  28   if [ "$(eval "echo \${$(echo get$(echo -ne $arch |
  29        sed 's/^\(.\).*/\1/g' | tr 'a-z' 'A-Z'; echo $arch |
  30        sed 's/^.\(.*\)/\1/g')):-false}")" = true ]
  31   then
  32      return 0;
  33   else
  34      return 1;
  35   fi;
  36 }
  37 
  38 getSparc="true"
  39 unset getIa64
  40 chkMirrorArchs sparc
  41 echo $?        # 0
  42                # True
  43 
  44 chkMirrorArchs Ia64
  45 echo $?        # 1
  46                # False
  47 
  48 # Notes:
  49 # -----
  50 # Even the to-be-substituted variable name part is built explicitly.
  51 # The parameters to the chkMirrorArchs calls are all lower case.
  52 # The variable name is composed of two parts: "get" and "Sparc" . . .


Example 9-25. Passing an indirect reference to awk

   1 #!/bin/bash
   2 
   3 #  Another version of the "column totaler" script
   4 #+ that adds up a specified column (of numbers) in the target file.
   5 #  This one uses indirect references.
   6 
   7 ARGS=2
   8 E_WRONGARGS=85
   9 
  10 if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
  11 then
  12    echo "Usage: `basename $0` filename column-number"
  13    exit $E_WRONGARGS
  14 fi
  15 
  16 filename=$1         # Name of file to operate on.
  17 column_number=$2    # Which column to total up.
  18 
  19 #===== Same as original script, up to this point =====#
  20 
  21 
  22 # A multi-line awk script is invoked by
  23 #   awk "
  24 #   ...
  25 #   ...
  26 #   ...
  27 #   "
  28 
  29 
  30 # Begin awk script.
  31 # ------------------------------------------------
  32 awk "
  33 
  34 { total += \$${column_number} # Indirect reference
  35 }
  36 END {
  37      print total
  38      }
  39 
  40      " "$filename"
  41 # ------------------------------------------------
  42 # End awk script.
  43 
  44 #  Indirect variable reference avoids the hassles
  45 #+ of referencing a shell variable within the embedded awk script.
  46 #  Thanks, Stephane Chazelas.
  47 
  48 
  49 exit $?

Caution

This method of indirect referencing is a bit tricky. If the second order variable changes its value, then the first order variable must be properly dereferenced (as in the above example). Fortunately, the ${!variable} notation introduced with version 2 of Bash (see Example 34-2 and Example A-24) makes indirect referencing more intuitive.