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-10 describes the most popular such shell variables.

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.

Table 13-10. Special Shell Variables Used in Scripts

Variable

Meaning

$#

The number of arguments.

$0

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. The value 0 denotes successful completion.

$$

The process id of the current process.

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

Get Learning Debian GNU/Linux 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.