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 />

Example 9−22. Passing an indirect reference to awk<br />

#!/bin/bash<br />

# Another version of the "column totaler" script<br />

# that adds up a specified column (of numbers) in the target file.<br />

# This uses indirect references.<br />

ARGS=2<br />

E_WRONGARGS=65<br />

if [ $# −ne "$ARGS" ] # Check for proper no. of command line args.<br />

then<br />

echo "Usage: `basename $0` filename column−number"<br />

exit $E_WRONGARGS<br />

fi<br />

filename=$1<br />

column_number=$2<br />

#===== Same as original script, up to this point =====#<br />

# A multi−line awk script is invoked by awk ' ..... '<br />

# Begin awk script.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

awk "<br />

{ total += \$${column_number} # indirect reference<br />

}<br />

END {<br />

print total<br />

}<br />

" "$filename"<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# End awk script.<br />

# Indirect variable reference avoids the hassles<br />

# of referencing a shell variable within the embedded awk script.<br />

# Thanks, Stephane Chazelas.<br />

exit 0<br />

This method of indirect referencing is a bit tricky. If the second order variable changes its value, then the<br />

first order variable must be properly dereferenced (as in the above example). Fortunately, the<br />

${!variable} notation introduced with version 2 of Bash (see Example 35−2) makes indirect<br />

referencing more intuitive.<br />

Chapter 9. Variables Revisited 95

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

Saved successfully!

Ooh no, something went wrong!