Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting | ||
---|---|---|
Prev | Chapter 9. Variables Revisited | Next |
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-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 a=letter_of_alphabet # Variable "a" holds the name of another variable. 6 letter_of_alphabet=z 7 8 echo 9 10 # Direct reference. 11 echo "a = $a" # a = letter_of_alphabet 12 13 # Indirect reference. 14 eval a=\$$a 15 echo "Now a = $a" # Now a = z 16 17 echo 18 19 20 # Now, let's try changing the second-order reference. 21 22 t=table_cell_3 23 table_cell_3=24 24 echo "\"table_cell_3\" = $table_cell_3" # "table_cell_3" = 24 25 echo -n "dereferenced \"t\" = "; eval echo \$$t # dereferenced "t" = 24 26 # In this simple case, the following also works (why?). 27 # eval t=\$$t; echo "\"t\" = $t" 28 29 echo 30 31 t=table_cell_3 32 NEW_VAL=387 33 table_cell_3=$NEW_VAL 34 echo "Changing value of \"table_cell_3\" to $NEW_VAL." 35 echo "\"table_cell_3\" now $table_cell_3" 36 echo -n "dereferenced \"t\" now "; eval echo \$$t 37 # "eval" takes the two arguments "echo" and "\$$t" (set equal to $table_cell_3) 38 39 echo 40 41 # (Thanks, Stephane Chazelas, for clearing up the above behavior.) 42 43 44 # Another method is the ${!t} notation, discussed in "Bash, version 2" section. 45 # See also ex78.sh. 46 47 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=65 9 10 if [ $# -ne "$ARGS" ] # Check for proper no. of command line args. 11 then 12 echo "Usage: `basename $0` filename column-number" 13 exit $E_WRONGARGS 14 fi 15 16 filename=$1 17 column_number=$2 18 19 #===== Same as original script, up to this point =====# 20 21 22 # A multi-line awk script is invoked by awk ' ..... ' 23 24 25 # Begin awk script. 26 # ------------------------------------------------ 27 awk " 28 29 { total += \$${column_number} # indirect reference 30 } 31 END { 32 print total 33 } 34 35 " "$filename" 36 # ------------------------------------------------ 37 # End awk script. 38 39 # Indirect variable reference avoids the hassles 40 #+ of referencing a shell variable within the embedded awk script. 41 # Thanks, Stephane Chazelas. 42 43 44 exit 0 |
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-23) makes indirect referencing more intuitive. |