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 $E_WRONGARGS<br />

fi<br />

filename=$1<br />

column_number=$2<br />

# Passing shell variables to the awk part of the script is a bit tricky.<br />

# See the awk documentation for more details.<br />

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

# Begin awk script.<br />

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

awk '<br />

{ total += $'"${column_number}"'<br />

}<br />

END {<br />

print total<br />

}<br />

' "$filename"<br />

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

# End awk script.<br />

# It may not be safe to pass shell variables to an embedded awk script,<br />

# so Stephane Chazelas proposes the following alternative:<br />

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

# awk −v column_number="$column_number" '<br />

# { total += $column_number<br />

# }<br />

# END {<br />

# print total<br />

# }' "$filename"<br />

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

exit 0<br />

For those scripts needing a single do−it−all tool, a Swiss army knife, there is Perl. Perl combines the<br />

capabilities of sed and awk, and throws in a large subset of C, to boot. It is modular and contains support for<br />

everything ranging from object−oriented programming up to and including the kitchen sink. Short Perl scripts<br />

lend themselves to embedding in shell scripts, and there may even be some substance to the claim that Perl<br />

can totally replace shell scripting (though the author of this document remains skeptical).<br />

Example 34−4. Perl embedded in a Bash script<br />

#!/bin/bash<br />

# Shell commands may precede the Perl script.<br />

echo "This precedes the embedded Perl script within \"$0\"."<br />

echo "==============================================================="<br />

perl −e 'print "This is an embedded Perl script.\n";'<br />

# Like sed, Perl also uses the "−e" option.<br />

echo "==============================================================="<br />

Chapter 34. Miscellany 339

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

Saved successfully!

Ooh no, something went wrong!