oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

An Introduction to Tiger Terminal, Part 4
Pages: 1, 2, 3, 4, 5


So far, we've created shell scripts using some of the simple Unix commands that we've learned from previous parts of this tutorial. Every shell program has a scripting language built in, and has special commands that are part of its own scripting language. The standard language for writing Unix scripts is the language of the Bourne shell. Most shells (sh, bash, ksh, and zsh) will run it. However, csh and tcsh run a different scripting language from these others. When OS X 10.3 (Panther) was released, with its new default bash shell, it caused a lot of grumbling among scripters who were comfortable using the default tcsh shell in Mac OS X 10.2 (Jaguar), because many commands have different syntax in bash.

The bash shell has a wide range of programming features, including user-defined functions, conditional statements (if/then), loops (for and while), mathematical operations, and variables. A variable is simply a name associated with a value: a string that represents data. Within bash, there are standard variables defined by the shell itself. Let's use two of them in our next shell script.

1. Open a new Terminal window, navigate to /Documents/scripts, and open nano, naming a new script,

Figure 22. nano

2. Create the following script, using your own comments, and tweak the text a bit to show your own flair!

Figure 23.

3. Save the script (^O) and exit (^X).

4. Don't forget to change permissions!

norburym15:~/documents/scripts norburym$ chmod +x

5. Run it!

Figure 24. The output of

Both $USER and $PWD are standard bash variables.

Here is another shell script, using the $HOME variable:

1. Open a new Terminal window, navigate to /Documents/scripts, and open nano naming a new script,

2. Type in the following script:

Figure 25.

3. Save the script (^O), exit (^X), and change permissions with chmod +x

4. Run this script:

Figure 26. The output of

You can also set your own variables. Here's a classic (and, sorry, woefully overused) example:

1. Still in your scripts folder, open nano and name a new script

Figure 27. nano

2. Type the following script, save it (^O), and exit (^X) nano:

Figure 28.

3. Permissions magic:

norburym15:~/documents/scripts norburym$ chmod +x

4. Run it!

Figure 29. The output of

Here, we've created our own variables, MY_GREETING and YOUR_RETORT, and assigned each of them a unique value: the string "Hello World!" and the string "Oh, go jump in the lake!" respectively. The equal sign (=) is called the assignment operator. There are no spaces on either side of the = symbol.

Go Get 'Em, Tiger!

We've obviously only scratched the surface here, but I hope these examples have given you ideas about how to harness the power of the Terminal by creating your own shell scripts! There are some really good books out there to help speed you on your way:


Return to the Mac DevCenter