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

#!/bin/bash<br />

ARGS=1 # Number of arguments expected.<br />

E_BADARGS=65 # Exit value if incorrect number of args passed.<br />

test $# −ne $ARGS && echo "Usage: `basename $0` $ARGS argument(s)" && exit $E_BADARGS<br />

# If condition−1 true (wrong number of args passed to script),<br />

# then the rest of the line executes, and script terminates.<br />

# Line below executes only if the above test fails.<br />

echo "Correct number of arguments passed to this script."<br />

exit 0<br />

# To check exit value, do a "echo $?" after script termination.<br />

Of course, an and list can also set variables to a default value.<br />

arg1=$@<br />

# Set $arg1 to command line arguments, if any.<br />

or list<br />

[ −z "$arg1" ] && arg1=DEFAULT<br />

# Set to DEFAULT if not specified on command line.<br />

command−1 || command−2 || command−3 || ... command−n<br />

Each command executes in turn for as long as the previous command returns false. At the first true<br />

return, the command chain terminates (the first command returning true is the last one to execute).<br />

This is obviously the inverse of the "and list".<br />

Example 25−3. Using "or lists" in combination with an "and list"<br />

#!/bin/bash<br />

# delete.sh, not−so−cunning file deletion utility.<br />

# Usage: delete filename<br />

E_BADARGS=65<br />

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

then<br />

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

exit $E_BADARGS # No arg? Bail out.<br />

else<br />

file=$1<br />

# Set filename.<br />

fi<br />

[ ! −f "$file" ] && echo "File \"$file\" not found. \<br />

Cowardly refusing to delete a nonexistent file."<br />

# AND LIST, to give error message if file not present.<br />

# Note echo message continued on to a second line with an escape.<br />

[ ! −f "$file" ] || (rm −f $file; echo "File \"$file\" deleted.")<br />

# OR LIST, to delete file if present.<br />

# Note logic inversion above.<br />

Chapter 25. List Constructs 290

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

Saved successfully!

Ooh no, something went wrong!