The $0 Variable
Whenever you execute a shell program, the shell automatically stores the name of the program inside the special variable $0. This can be used to advantage when you have two or more programs that are linked under different names and you want to know which one was executed. It's also useful for displaying error messages because it removes the dependency of the filename from the program. If the name of the program is referenced by $0, subsequently renaming the program will not require the program to be edited:
$ cat lu
#
# Look someone up in the phone book
#
if [ "$#" -ne 1 ]
then
echo "Incorrect number of arguments"
echo "Usage: $0 name"
exit 1
fi
name=$1
grep "$name" $PHONEBOOK
if [ $? -ne 0 ]
then
echo "I couldn't find $name in the phone book"
fi
$ PHONEBOOK=$HOME/phonebook
$ export PHONEBOOK
$ lu Teri
Teri Zak 201-555-6000
$ lu Teri Zak
Incorrect number of arguments
Usage: lu name
$ mv lu lookup Rename it
$ lookup Teri Zak See what happens now
Incorrect number of arguments
Usage: lookup name
$
|
No comments:
Post a Comment