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.

336<br />

CHAPTER 19 EXTENDING THE POWER OF DARWIN<br />

The other common loop is the for loop. Rather than relying on a true/false condition like<br />

the while and until loops, a for loop iterates over all the elements in a list. For example, a simple<br />

script to echo back the command-line arguments could look like this:<br />

#!/bin/sh<br />

echo "The command line arguments given to $0 are: "<br />

for x in $@<br />

do<br />

echo $x<br />

done<br />

NOTE $@ is a special variable that contains each command-line argument together in a single<br />

variable.<br />

You may find that there is situation where you need to get out of a loop before it completes,<br />

which is accomplished with either the break or continue command. The break command will<br />

immediately stop the current loop pass and exit the loop process entirely (that is, the script<br />

will continue immediately following the loop). The continue command will cause a halt in the<br />

current pass through the loop but will continue the loop process if the conditions are still met.<br />

Input and Output<br />

Many scripts you write will need to provide output, and often you may want a script to prompt<br />

for input as well. In the previous chapter, you learned most of the basics you need in order to<br />

output text either to the terminal or to a file using the echo command (with redirection if you<br />

want to write the output to a file), but there is also the printf command that provides more<br />

options in how your output is presented. To get information into a script, you can use the read<br />

command, which will provide a prompt at the command line for input.<br />

The following script (enhanced from previously) shows how read and printf work (line<br />

numbers have been added for reference):<br />

1: #!/bin/sh<br />

2:<br />

3: printf "Please enter your input here: "<br />

4: read input<br />

5: set $input<br />

6: c=$#<br />

7: printf "You entered The following: "<br />

8: for x in $@<br />

9: do<br />

10: c=`expr $c - 1`<br />

11: if [ $c -gt 0 ]<br />

12: then<br />

13: printf "\"$x\", "<br />

14: else<br />

15: printf "and \"$x\".\n"<br />

16: fi<br />

17: done<br />

When you run this script, you get something along the lines of this:<br />

Please enter your input here: hello goodbye dogcow<br />

You entered The following: "hello", "goodbye", and "dogcow".

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

Saved successfully!

Ooh no, something went wrong!