Introducing UNIX and Linux |
Introduction to shellsOverview |
Scripts with argumentsJust as a UNIX command can take arguments, so can a script.
After all, a script is a command written by a user. The first
argument of a script is referred to within the script as
Now run that script, but give it two arguments:
There are some other 'variable names' that have special meanings
when used within a script. The name of the script (i.e. the name of
the file containing the script) is denoted by This script is $0, and it has $# arguments First argument is $1 The output we would get would be:
Note that When a script is given many arguments, accessing them one-by-one
using positional parameters is often awkward. We can use
for i in $* do echo $i done and call it
would be equivalent to running a script containing: for i in jo sam george do echo $i done We must be careful, though; the shell will strip out quotes before passing arguments to a command, and we need to be able to handle
in a sensible manner. To this end we can use
indicating that the quotes have been stripped before the
arguments have been passed to
the quotes are stripped from the arguments, which are then
enclosed by a new pair of quotes. Thus the string
If, however,
If a script requires an indeterminate number of arguments, you
may wish to discard the earlier ones - for instance, if they are
options and you have finished processing all the options. The
command shift will remove Worked exampleWrite a script called
IFLAG=no
if [ "$#" -gt 0 ] # Make sure there are some files
then if [ "$1" = "-i" ] # Check if the option is called
then IFLAG=yes # If so, reset the flag ...
shift # and delete the argument
fi
fi
for i in "$@" # Go through each file in turn
do
if [ "$IFLAG" = "yes" ] # If "-i" ...
then echo "Paging $i" # output message ...
echo "Press Return to continue"
read j # wait for Return
fi
more "$i" # Page the file
done
|
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck