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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

names instead. This makes the script easier to understand and permits making changes and updates<br />

without breaking the application.<br />

if [ −f /var/log/messages ]<br />

then<br />

...<br />

fi<br />

# A year later, you decide to change the script to check /var/log/syslog.<br />

# It is now necessary to manually change the script, instance by instance,<br />

# and hope nothing breaks.<br />

# A better way:<br />

LOGFILE=/var/log/messages # Only line that needs to be changed.<br />

if [ −f "$LOGFILE" ]<br />

then<br />

...<br />

fi<br />

• Choose descriptive names for variables and functions.<br />

fl=`ls −al $dirname`<br />

# Cryptic.<br />

file_listing=`ls −al $dirname` # Better.<br />

MAXVAL=10 # All caps used for a script constant.<br />

while [ "$index" −le "$MAXVAL" ]<br />

...<br />

E_NOTFOUND=75<br />

if [ ! −e "$filename" ]<br />

then<br />

echo "File $filename not found."<br />

exit $E_NOTFOUND<br />

fi<br />

# Uppercase for an errorcode,<br />

# and name begins with "E_".<br />

MAIL_DIRECTORY=/var/spool/mail/bozo # Uppercase for an environmental variable.<br />

export MAIL_DIRECTORY<br />

GetAnswer ()<br />

{<br />

prompt=$1<br />

echo −n $prompt<br />

read answer<br />

return $answer<br />

}<br />

# Mixed case works well for a function.<br />

GetAnswer "What is your favorite number? "<br />

favorite_number=$?<br />

echo $favorite_number<br />

_uservariable=23<br />

# Permissable, but not recommended.<br />

# It's better for user−defined variables not to start with an underscore.<br />

# Leave that for system variables.<br />

• Use exit codes in a systematic and meaningful way.<br />

E_WRONG_ARGS=65<br />

...<br />

...<br />

exit $E_WRONG_ARGS<br />

Chapter 33. Scripting With Style 334

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

Saved successfully!

Ooh no, something went wrong!