Once you have mastered simple shell scripts, you can do more
complex shell programming. This chapter introduces ways to pass
information to a shell program, how to execute commands conditionally,
and how to get data from the keyboard during the execution of a
shell program.
All of the constructs of shell programming can be executed
in two ways: you can type the commands into a file so they will
all be executed when the file name is entered (after changing the
permission), or you can enter the commands directly into the shell
(just as you enter commands like "date").
When you enter shell constructs directly into the shell, you
can either type them on the same line (and press return to execute
them), or you can type them over several lines. For example, we
can type the following construct two ways (don't worry what the
construct actually does, just how it can be typed). First on one
line:
if test -d /d1; then echo "/d1 is a directory"; fi |
Then on several lines:
if test -d /d1 then echo "/d1 is a directory" fi |
Typing the command on one line is simple to do in the shell.
If you type the command on several lines, you will receive a secondary
prompt (which you can define in the PS2
variable). The secondary prompt is usually a ">".
So, if you were to type the above command on several lines, the
screen would look like:
$ if test -d /d1 > then > echo "/d1 is a directory" > fi /d1 is a directory $ |
where "$" is the system prompt.
What is more, you can create shells from programs such as
notes, mail
and most editors (such as vi),
and execute shell commands from these shells. Running a shell from
another program is usually called "forking" a
shell. It may be useful if you are writing a program and wish to
test the program: you can edit the program in vi,
fork a shell from vi
(by typing ":sh"),
execute the program to see if it works, exit the new shell (by typing
CTRL-D),
and be right back in the editor to make any changes.