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

fi<br />

if [ "$1" −eq "$2" ]<br />

then<br />

return $EQUAL<br />

else<br />

if [ "$1" −gt "$2" ]<br />

then<br />

return $1<br />

else<br />

return $2<br />

fi<br />

fi<br />

}<br />

max2 33 34<br />

return_val=$?<br />

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

then<br />

echo "Need to pass two parameters to the function."<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 />

# Exercise (easy):<br />

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

# Convert this to an interactive script,<br />

#+ that is, have the script ask for input (two numbers).<br />

For a function to return a string or array, use a dedicated variable.<br />

count_lines_in_etc_passwd()<br />

{<br />

[[ −r /etc/passwd ]] && REPLY=$(echo $(wc −l < /etc/passwd))<br />

# If /etc/passwd is readable, set REPLY to line count.<br />

# Returns both a parameter value and status information.<br />

}<br />

if count_lines_in_etc_passwd<br />

then<br />

echo "There are $REPLY lines in /etc/passwd."<br />

else<br />

echo "Cannot count lines in /etc/passwd."<br />

fi<br />

# Thanks, S.C.<br />

Example 23−4. Converting numbers to Roman numerals<br />

#!/bin/bash<br />

# Arabic number to Roman numeral conversion<br />

Chapter 23. Functions 278

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

Saved successfully!

Ooh no, something went wrong!