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.

# Range: 0 − 200<br />

# It's crude, but it works.<br />

# Extending the range and otherwise improving the script is left as an exercise.<br />

# Usage: roman number−to−convert<br />

LIMIT=200<br />

E_ARG_ERR=65<br />

E_OUT_OF_RANGE=66<br />

if [ −z "$1" ]<br />

then<br />

echo "Usage: `basename $0` number−to−convert"<br />

exit $E_ARG_ERR<br />

fi<br />

num=$1<br />

if [ "$num" −gt $LIMIT ]<br />

then<br />

echo "Out of range!"<br />

exit $E_OUT_OF_RANGE<br />

fi<br />

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

to_roman () # Must declare function before first call to it.<br />

{<br />

number=$1<br />

factor=$2<br />

rchar=$3<br />

let "remainder = number − factor"<br />

while [ "$remainder" −ge 0 ]<br />

do<br />

echo −n $rchar<br />

let "number −= factor"<br />

let "remainder = number − factor"<br />

done<br />

return $number<br />

# Exercise:<br />

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

# Explain how this function works.<br />

# Hint: division by successive subtraction.<br />

}<br />

to_roman $num 100 C<br />

num=$?<br />

to_roman $num 90 LXXXX<br />

num=$?<br />

to_roman $num 50 L<br />

num=$?<br />

to_roman $num 40 XL<br />

num=$?<br />

to_roman $num 10 X<br />

num=$?<br />

to_roman $num 9 IX<br />

num=$?<br />

to_roman $num 5 V<br />

num=$?<br />

to_roman $num 4 IV<br />

num=$?<br />

to_roman $num 1 I<br />

Chapter 23. Functions 279

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

Saved successfully!

Ooh no, something went wrong!