05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

334<br />

CHAPTER 19 EXTENDING THE POWER OF DARWIN<br />

One thing to keep in mind is that once the condition is met, the script will execute that block<br />

and then exit the if block entirely, so if condition1 is met, the script will not check for condition2<br />

or run the code in that block.<br />

There are a number of ways to create conditional statements; one of the most common is to<br />

use a mathematical test condition as listed in Table 19-1 (the Bash alternate expressions will<br />

work only with Bash and not a traditional Bourne shell).<br />

Table 19-1. Mathematic Test Expressions for sh and Bash<br />

Expression (sh) Bash Alternate Result<br />

$x -eq $y $x == $y True if $x is equal to $y<br />

$x -ne $y $x != $y True if $x is not equal to $y<br />

$x -lt $y $x < $y True if $x is less than $y<br />

$x -gt $y $x > $y True if $x is greater than $y<br />

$x -le $y $x = $y True if $x is greater than or equal to $y<br />

Another common conditional statement is to check on the existence of a file or directory.<br />

This is especially handy if you are creating workflow or other scripts that interact with the file<br />

system. An if statement that checks for the existence of a particular file would look like this:<br />

if [ -e /path/to/file ]<br />

then<br />

If file exists do this<br />

else<br />

If file doesn't exist do this<br />

fi<br />

Here the -e option checks for the existence of the file. Table 19-2 lists some possible options.<br />

Table 19-2. Common Options for Testing File Attributes in Shell Scripts<br />

Option Result<br />

-e file True if the file exists at all<br />

-f file True if file exists and it is a regular file<br />

-d file True if file exists and it is a directory<br />

-r file True if file exists and it is readable<br />

-w file True if file exists and it is writeable<br />

-x file True if file exists and it is executable<br />

It is also possible to test multiple conditions using logical and/or statements. This allows you<br />

to check either whether multiple statements are all true or whether one of many statements is<br />

true. This is done using either && or || (that’s the long bar over the \ key) between the conditions.<br />

[ condition1 ] && [ condition2 ] will return true if both conditions are true, while [ condition1 ]<br />

|| [ condition2 ] will return true if either condition is true.

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

Saved successfully!

Ooh no, something went wrong!