UNIX Shell
Scripting
The test command
The test command is the primary way to control if
statements or loops in UNIX shell scripts.
The test command either begins with the word "test" or has the
command enclosed in square brackets
"[", "]".
There must be spaces around the square brackets. See p. 719 in Sobell for more information
about the various tests. Note it is
very important not to have a shell variable with the name of "test".
The if Statement
The form of the
if statement is as follows. Note that
the keywords then and fi must appear on their own line.
if [ test-command ]
then
command(s)
fi
The if statement can also have multiple "elif"
clauses or a final "else" clause.
The form of an if statement with two elif clauses and an else clause is:
if [ test-comand ]
then
command(s)
elif [ test-command ]
then
command(s)
elif [ test-command ]
then
command(s)
else
command(s)
fi
The while and until Statements
The form of the while and until statements are as
follows:
while [ test-command ] until [
test-command ]
do do
command(s) command(s)
done done
In a while loop, the command(s) will continue to execute
WHILE the test-command is true. In an
until loop, the command(s) will continue to execute UNTIL the test-command is
true.
The for statement
The form of the for statement is as follows:
for var-name
in value-list for var1 in apple
banana pear grape
do do
command(s) echo value
of '$var1' is
$var1
done done
The for loop will loop once for each value in the value-list. The value in var-name will change each time to match
the values in the value-list. In the example the loop will execute four
times, var1 will have the value of apple the first time thorugh the loop, banana the second time, pear the third time and grape the fourth time.
If the value-list
is omitted (and the keyword in), the
var-name will take on the values from the command line arguments.
Comments
To put a comment in a script, use the # symbol. The # symbol must be the first letter of a
word. Everything after the # symbol until the end of the line is ignored. Note: This does not work if you attempt to
put a comment on the first line of the shell script. When the first character of a script is the # symbol, the script
uses the rest of the first line as the path which tells the location of the
shell program. This implies that the
first line of a shell script must never be a comment. The first line of a shell script is often the colon
character. The colon is the NULL command
in UNIX shell scripts. The first line
of the shell script could be the location of the BOURNE shell program following
a # symbol (i.e. "#!/bin/sh").
• Write a shell script that prompts the user
to guess for a number from 1 to 10. The
shell script should loop until the user enters to correct number. This is very similar to the secret name
guess shell script the book has on page 318.