11.3. Shell Programming

You can do a lot with Unix commands, but if you have to issue the same commands over and over, it can become pretty tedious. Luckily, it's possible to combine a sequence of commands into a script, which can be run as often as you like. This section shows you how to write and run scripts.

Bash also offers a number of rudimentary programming constructions, such as conditional branching and loops, which may be familiar to you from other programming languages. Although these aspects of Bash can be used when working interactively, they are most useful when writing shell scripts. The programming aspects of Bash are also covered in this section.

11.3.1. Scripts

Bash scripts are made up of nothing more or less than the commands you enter at the prompt when working interactively. If you enter these commands in a text file, one per line, in the order they are issued, and you change the permissions of the file so that it can be executed, you have a Bash Shell script.

Take this interactive session:

Macintosh:~ sample$ cd ~/Desktop/
Macintosh:~/Desktop sample$ touch blah
Macintosh:~/Desktop sample$ mkdir blahdir
Macintosh:~/Desktop sample$ mv blah blahdir/

If you find yourself repeating these commands often, you might consider inserting them into a script. The script would look like this:

cd ~/Desktop/
touch blah
mkdir blahdir
mv blah blahdir

The script simply contains the same commands that were entered at the interactive prompt. The ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.