UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.12 Parameter Substitution Chapter 45
Shell Programming for the Initiated
Next: 45.14 Finding the Last Command-Line Argument
 

45.13 Save Disk Space and Programming: Multiple Names for a Program

If you're writing:

you might want to write just one program and make links (18.4, 18.3) to it instead. The program can find the name you called it with and, through case or test commands, work in different ways. For instance, the Berkeley UNIX commands ex, vi, view, edit, and others are all links to the same executable file. This takes less disk space and makes maintenance easier. It's usually only sensible when most of the code is the same in each program. If the program is full of name tests and lots of separate code, this technique may be more trouble than it's worth.

Depending on how the script program is called, this name can be a simple relative pathname like prog or ./prog-it can also be an absolute pathname like /usr/joe/bin/prog (article 14.2 explains pathnames). There are a couple of ways to handle this in a shell script. If there's just one main piece of code in the script, as in the lf script (16.7), a case that tests $0 might be best. The asterisk (*) wildcard at the start of each case (see article 44.6) handles the different pathnames that might be used to call the script:

case "$0" in
*name1)
    ...do this when called as name1...
    ;;
*name2)
    ...do this when called as name2...
    ;;
    ...
*)  ...print error and exit if $0 doesn't match...
    ;;
esac

You might also want to use basename (45.18) to strip off any leading pathname and store the cleaned-up $0 in a variable called myname. You can test $myname anywhere in the script and also use it for error messages:

myname=`basename $0`
   ...
case "$myname" in
   ...

echo "$myname: aborting; error in xxxxxx" 1>&2
   ...

- JP


Previous: 45.12 Parameter Substitution UNIX Power ToolsNext: 45.14 Finding the Last Command-Line Argument
45.12 Parameter Substitution Book Index45.14 Finding the Last Command-Line Argument

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System