27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

exit 0<br />

# Script will not exit here.<br />

9.5. Indirect References to Variables<br />

Assume that the value of a variable is the name of a second variable. Is it somehow possible to retrieve the<br />

value of this second variable from the first one? For example, if a=letter_of_alphabet and<br />

letter_of_alphabet=z, can a reference to a return z? This can indeed be done, and it is called an<br />

indirect reference. It uses the unusual eval var1=\$$var2 notation.<br />

Example 9−21. Indirect References<br />

#!/bin/bash<br />

# Indirect variable referencing.<br />

a=letter_of_alphabet<br />

letter_of_alphabet=z<br />

echo<br />

# Direct reference.<br />

echo "a = $a"<br />

# Indirect reference.<br />

eval a=\$$a<br />

echo "Now a = $a"<br />

echo<br />

# Now, let's try changing the second order reference.<br />

t=table_cell_3<br />

table_cell_3=24<br />

echo "\"table_cell_3\" = $table_cell_3"<br />

echo −n "dereferenced \"t\" = "; eval echo \$$t<br />

# In this simple case,<br />

# eval t=\$$t; echo "\"t\" = $t"<br />

# also works (why?).<br />

echo<br />

t=table_cell_3<br />

NEW_VAL=387<br />

table_cell_3=$NEW_VAL<br />

echo "Changing value of \"table_cell_3\" to $NEW_VAL."<br />

echo "\"table_cell_3\" now $table_cell_3"<br />

echo −n "dereferenced \"t\" now "; eval echo \$$t<br />

# "eval" takes the two arguments "echo" and "\$$t" (set equal to $table_cell_3)<br />

echo<br />

# (Thanks, S.C., for clearing up the above behavior.)<br />

# Another method is the ${!t} notation, discussed in "Bash, version 2" section.<br />

# See also example "ex78.sh".<br />

Chapter 9. Variables Revisited 94

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!