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.

Chapter 25. List Constructs<br />

The "and list" and "or list" constructs provide a means of processing a number of commands consecutively.<br />

These can effectively replace complex nested if/then or even case statements.<br />

Chaining together commands<br />

and list<br />

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

Each command executes in turn provided that the previous command has given a return value of true<br />

(zero). At the first false (non−zero) return, the command chain terminates (the first command<br />

returning false is the last one to execute).<br />

Example 25−1. Using an "and list" to test for command−line arguments<br />

#!/bin/bash<br />

# "and list"<br />

if [ ! −z "$1" ] && echo "Argument #1 = $1" && [ ! −z "$2" ] && echo "Argument #2 = $2"<br />

then<br />

echo "At least 2 arguments passed to script."<br />

# All the chained commands return true.<br />

else<br />

echo "Less than 2 arguments passed to script."<br />

# At least one of the chained commands returns false.<br />

fi<br />

# Note that "if [ ! −z $1 ]" works, but its supposed equivalent,<br />

# if [ −n $1 ] does not. However, quoting fixes this.<br />

# if [ −n "$1" ] works. Careful!<br />

# It is best to always quote tested variables.<br />

# This accomplishes the same thing, using "pure" if/then statements.<br />

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

then<br />

echo "Argument #1 = $1"<br />

fi<br />

if [ ! −z "$2" ]<br />

then<br />

echo "Argument #2 = $2"<br />

echo "At least 2 arguments passed to script."<br />

else<br />

echo "Less than 2 arguments passed to script."<br />

fi<br />

# It's longer and less elegant than using an "and list".<br />

exit 0<br />

Example 25−2. Another command−line arg test using an "and list"<br />

Chapter 25. List Constructs 289

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

Saved successfully!

Ooh no, something went wrong!