O'Reilly logo

Learning Red Hat Enterprise Linux & Fedora, Fourth Edition by Bill McCarty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

Table 12-6. 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; 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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required