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

then<br />

# then<br />

let "return_val = (( 0 − $return_val ))" # renormalize to positive.<br />

fi<br />

# "Absolute value" of $return_val.<br />

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

if [ "$return_val" −eq "$E_NPARAM_ERR" ]<br />

then<br />

# Parameter error "flag" gets sign changed, too.<br />

echo "Error: Too few parameters."<br />

elif [ "$return_val" −eq "$EQUAL" ]<br />

then<br />

echo "The two numbers are equal."<br />

else<br />

echo "The larger of the two numbers is $return_val."<br />

fi<br />

exit 0<br />

See also Example A−8.<br />

Exercise: Using what we have just learned, extend the previous Roman numerals example to<br />

accept arbitrarily large input.<br />

Redirection<br />

Redirecting the stdin of a function<br />

A function is essentially a code block, which means its stdin can be redirected (as in Example 3−1).<br />

Example 23−7. Real name from username<br />

#!/bin/bash<br />

# From username, gets "real name" from /etc/passwd.<br />

ARGCOUNT=1 # Expect one arg.<br />

E_WRONGARGS=65<br />

file=/etc/passwd<br />

pattern=$1<br />

if [ $# −ne "$ARGCOUNT" ]<br />

then<br />

echo "Usage: `basename $0` USERNAME"<br />

exit $E_WRONGARGS<br />

fi<br />

file_excerpt () # Scan file for pattern, the print relevant portion of line.<br />

{<br />

while read line # while does not necessarily need "[ condition]"<br />

do<br />

echo "$line" | grep $1 | awk −F":" '{ print $5 }' # Have awk use ":" delimiter.<br />

done<br />

}

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

Saved successfully!

Ooh no, something went wrong!