Creating Shell Programs

To create a shell program, shell commands are combined in various ways to accomplish the user's needs.  This is the fun part.  Users can create procedures by entering shell commands into a UNIX file via any of the available editors.  To make the shell file executable, all you have to do is change its mode:

chmod 755 shellproc

or

chmod +x shellproc

Rules of Thumb

  1. Try each command line interactively, to make sure it works correctly.

  2. Build the program using one of the editors interactively, one line at a time, testing as you go.

Option and Argument Lists

Each portion of a shell command line is assigned to special default variable name $0 to $9.  The $0 argument is always the name of the shell program.  The remainder of the variables $1 to $9 are the actual arguments the user of your shell supplied.  The $# variable stores the number of arguments passed.

The shift command is used with while loops to process arguments:

while [ "$1" ]
do
        process $1
        shift
done

This example processes each argument and then shifts the remaining arguments. When there are no more arguments, the if statement test will return a false value to the while loop and the command will exit successfully.  shift makes looping through arguments simple and straightforward.  shift is also useful when processing two or more arguments at a time:

while [ "$1" -a "$2" ] 
do 
        process $1 $2 
        shift ; shift 
done 

It should be noted that the shell only allows for the arguments $0 to $9. If you have more than nine arguments, then you must use shift to access the arguments beyond $9.  The shell will not recognize $10 as an argument reference; it will interpret this as the $1 followed by a 0 character.

Other special variables:

$* Pass all the arguments to the receiving command as a single argument.
$@ Pass the arguments to the receiving command as they were originally specified.
$? Exit status of the last command.

Back to CTEC1863 Lab #10