UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.21 Picking a Name for a New Command Chapter 44
Shell Programming for the Uninitiated
Next: 44.23 Reading Files with the . and source Commands
 

44.22 Finding a Program Name; Multiple Program Names

A UNIX program should use its name as the first word in error messages it prints. That's important when the program is running in the background or as part of a pipeline - you need to know which program has the problem:

someprog: quitting: can't read file xxxxxx

It's tempting to use just the program name in the echo commands:

echo "someprog: quitting: can't read file $file" 1>&2

but if you ever change the program name, it's easy to forget to fix the messages. A better way is to store the program name in a shell variable at the top of the script file, and then use the variable in all messages:

myname=someprog
   ...
echo "$myname: quitting: can't read file $file" 1>&2

Even better, use the $0 parameter. The shell automatically puts the script's name there. But $0 can have the absolute pathname of the script, such as /xxx/yyy/bin/someprog. The basename (45.18) program fixes this: basename strips off the head of a pathname - everything but the filename.

For example, if $0 is /u/ehuser/bin/sendit, then:

myname="`basename $0`"

would put sendit into the myname shell variable.

Just as you can make links (18.3) to give UNIX files several names, you can use links to give your program several names (45.13). For instance, see the script named ll, lf, lg (...and so on) in article 16.7. Use $0 to get the current name of the program.

- JP


Previous: 44.21 Picking a Name for a New Command UNIX Power ToolsNext: 44.23 Reading Files with the . and source Commands
44.21 Picking a Name for a New Command Book Index44.23 Reading Files with the . and source Commands

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