05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Command Substitution<br />

Another way to assign a variable is through command substitution. This allows you to work<br />

with the result of any shell command by enclosing the command with backticks (the ` character<br />

below the Esc key on most <strong>Mac</strong> keyboards). This allows you to take advantage of any shell command,<br />

making up for most of the shell’s natural shortcomings. For example, the Bourne shell<br />

doesn’t have built-in capabilities for simple arithmetic; however, using command substitution,<br />

you can take advantage of command-line executables that do this for you anyway, like this:<br />

#!/bin/sh<br />

x=2<br />

y=3<br />

z=`expr $x + $y`<br />

echo $z<br />

This little script uses the expr executable to do the math for you and then prints 5, which is<br />

what you’d expect.<br />

NOTE The Bash shell actually does have built-in arithmetic capability, so if you were so<br />

inclined, you could replace the z=`expr $x + $y` line with let z=$x+$y and get the same<br />

results.<br />

Controlling the Flow<br />

The ability to control the flow of a script makes it much more adaptable and useful. There are<br />

two primary ways to control the flow of a script: conditionals, which will execute commands if<br />

certain conditions are met, and loops, which can repeat commands over and over a predetermined<br />

number of times.<br />

Conditional Statements<br />

There are two common conditional statements available in shell scripts: if statements and case<br />

statements. An if statement checks to see whether a condition is true or false. If the condition is<br />

true, then a block of code is run; if it is false, an else block is run. The whole thing looks something<br />

like this:<br />

if [ condition ]<br />

then<br />

condition is met block<br />

else<br />

condition not met block<br />

fi<br />

The fi at the end signals the end of the if statement.<br />

One other thing that can be added to respond to multiple conditions is the elif condition.<br />

This allows you to create logic like this:<br />

if [ condition1 ]<br />

then<br />

condition1 block<br />

elif [ condition2 ]<br />

condition2 block<br />

elif [ condition3 ]<br />

...<br />

else<br />

no conditions met block<br />

fi<br />

CHAPTER 19 EXTENDING THE POWER OF DARWIN 333

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

Saved successfully!

Ooh no, something went wrong!