📄 ivr.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Indirect References</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Variables Revisited"HREF="variables2.html"><LINKREL="PREVIOUS"TITLE="Typing variables: declare or typeset"HREF="declareref.html"><LINKREL="NEXT"TITLE="$RANDOM: generate random integer"HREF="randomvar.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="SECT1"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="declareref.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 9. Variables Revisited</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="randomvar.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="IVR"></A>9.5. Indirect References</H1><P><ANAME="IVRREF"></A></P><P>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 <TTCLASS="REPLACEABLE"><I>a=letter_of_alphabet</I></TT> and <TTCLASS="REPLACEABLE"><I>letter_of_alphabet=z</I></TT>, can a reference to <TTCLASS="REPLACEABLE"><I>a</I></TT> return <TTCLASS="REPLACEABLE"><I>z</I></TT>? This can indeed be done, and it is called an <ICLASS="FIRSTTERM">indirect reference</I>. It uses the unusual <TTCLASS="REPLACEABLE"><I>eval var1=\$$var2</I></TT> notation.</P><DIVCLASS="EXAMPLE"><HR><ANAME="INDREF"></A><P><B>Example 9-24. Indirect Variable References</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 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</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="IRRREF"></A>Of what practical use is indirect referencing of variables? It gives Bash a little of the functionality of <AHREF="variables.html#POINTERREF">pointers</A> in <ICLASS="FIRSTTERM">C</I>, for instance, in <AHREF="bash2.html#RESISTOR">table lookup</A>. And, it also has some other very interesting applications. . . .</P><P> Nils Radtke shows how to build <SPANCLASS="QUOTE">"dynamic"</SPAN> variable names and evaluate their contents. This can be useful when <AHREF="internal.html#SOURCEREF">sourcing</A> configuration files. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 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" . . .</PRE></TD></TR></TABLE> </P><DIVCLASS="EXAMPLE"><HR><ANAME="COLTOTALER2"></A><P><B>Example 9-25. Passing an indirect reference to <ICLASS="FIRSTTERM">awk</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 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</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="CAUTION"><TABLECLASS="CAUTION"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/caution.png"HSPACE="5"ALT="Caution"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>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). <ANAME="IVR2"></A>Fortunately, the <TTCLASS="REPLACEABLE"><I>${!variable}</I></TT> notation introduced with <AHREF="bash2.html#BASH2REF">version 2</A> of Bash (see <AHREF="bash2.html#EX78">Example 34-2</A> and <AHREF="contributed-scripts.html#HASHEX2">Example A-24</A>) makes indirect referencing more intuitive.</P></TD></TR></TABLE></DIV><TABLECLASS="SIDEBAR"BORDER="1"CELLPADDING="5"><TR><TD><DIVCLASS="SIDEBAR"><ANAME="AEN5689"></A><P>Bash does not support pointer arithmetic, and this severely limits the usefulness of indirect referencing. In fact, indirect referencing in a scripting language is, at best, an ugly kludge.</P></DIV></TD></TR></TABLE></DIV><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="declareref.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html"ACCESSKEY="H">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="randomvar.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Typing variables: <BCLASS="COMMAND">declare</B> or <BCLASS="COMMAND">typeset</B></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="variables2.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">$RANDOM: generate random integer</TD></TR></TABLE></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -