Understanding Shell Scripts

This section explains how more advanced shell scripts work. The information is also adequate to equip you to write many of your own useful shell scripts. The section begins by showing how to process a script’s arguments. Then it shows how to perform conditional and iterative operations.

Processing Arguments

You can easily write scripts that process arguments, because a set of special shell variables holds the values of arguments specified when your script is invoked. Table 13-6 describes the most popular such shell variables.

Table 13-6. Special Shell Variables Used in Scripts




The number of arguments.


The command name.

$1, $2, ... ,$9

The individual arguments of the command.


The entire list of arguments, treated as a single word.


The entire list of arguments, treated as a series of words.


The exit status of the previous command; a value of 0 denotes a successful completion.


The ID of the current process.

For example, here’s a simple one-line script that prints the value of its second argument:

echo My second argument has the value $2.

Suppose you store this script in the file second, change its access mode to permit execution, and invoke it as follows:

               ./second a b c

The script will print the output:

My second argument has the value b.

Notice that the shell provides variables for accessing only nine arguments. Nevertheless, you can access more than nine arguments. The key to doing so is the shift command, ...

Get Learning Red Hat Linux, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.