9.5. Indirect References to Variables

Assume that the value of a variable is the name of a second variable. Is it somehow possible to retrieve the value of this second variable from the first one? For example, if a=letter_of_alphabet and letter_of_alphabet=z, can a reference to a return z? This can indeed be done, and it is called an indirect reference. It uses the unusual eval var1=\$$var2 notation.

Example 9-16. Indirect References

#!/bin/bash
# Indirect variable referencing.

a=letter_of_alphabet
letter_of_alphabet=z

echo

# Direct reference.
echo "a = $a"

# Indirect reference.
eval a=\$$a
echo "Now a = $a"

echo


# Now, let's try changing the second order reference.

t=table_cell_3
table_cell_3=24
echo "\"table_cell_3\" = $table_cell_3"
echo -n "dereferenced \"t\" = "; eval echo \$$t
# In this simple case,
#   eval t=\$$t; echo "\"t\" = $t"
# also works (why?).

echo

t=table_cell_3
NEW_VAL=387
table_cell_3=$NEW_VAL
echo "Changing value of \"table_cell_3\" to $NEW_VAL."
echo "\"table_cell_3\" now $table_cell_3"
echo -n "dereferenced \"t\" now "; eval echo \$$t
# "eval" takes the two arguments "echo" and "\$$t" (set equal to $table_cell_3)
echo

# (Thanks, S.C., for clearing up the above behavior.)


# Another method is the ${!t} notation, discussed in "Bash, version 2" section.
# See also example "ex78.sh".

exit 0

Example 9-17. Passing an indirect reference to awk

#!/bin/bash

# Another version of the "column totaler" script
# that adds up a specified column (of numbers) in the target file.
# This uses indirect references.

ARGS=2
E_WRONGARGS=65

if [ $# -ne "$ARGS" ] # Check for proper no. of command line args.
then
   echo "Usage: `basename $0` filename column-number"
   exit $E_WRONGARGS
fi

filename=$1
column_number=$2

#===== Same as original script, up to this point =====#


# A multi-line awk script is invoked by   awk ' ..... '


# Begin awk script.
# ------------------------------------------------
awk "

{ total += \$${column_number} # indirect reference
}
END {
     print total
     }

     " "$filename"
# ------------------------------------------------
# End awk script.

# Indirect variable reference avoids the hassles
# of referencing a shell variable within the embedded awk script.
# Thanks, Stephane Chazelas.


exit 0

Caution

This method of indirect referencing is a bit tricky. If the second order variable changes its value, then the 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 35-2) makes indirect referencing more intuitive.