Skip to Main Content
Learning Debian GNU/Linux
book

Learning Debian GNU/Linux

by Bill McCarty
October 1999
Beginner to intermediate content levelBeginner to intermediate
360 pages
10h 18m
English
O'Reilly Media, Inc.
Content preview from Learning Debian GNU/Linux

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux in Action

Linux in Action

David Clinton

Publisher Resources

ISBN: 1565927052Supplemental ContentCatalog PageErrata