Shell scripts should not use absolute paths for programs

July 13, 2009

There is a certain habit in shell scripts of referring to uncommon programs by their absolute path; for example, if you need to run lsof, people will write '/usr/sbin/lsof ....' in their shell script. We do a certain amount of that here, and then recently one of our shell scripts started reporting:

netwatch: line 15: /usr/sbin/lsof: No such file or directory

You see, you shouldn't do this, because every so often Unix vendors change where they put commands (or, in multi-vendor environments, two vendors disagree about it). If you used hard-coded paths, your script just broke.

(In this case, Ubuntu 6.06 put lsof in /usr/sbin and Ubuntu 8.04 moved it to /usr/bin, probably on the sensible grounds that it's useful for ordinary users too.)

The right way to do this is to add the directory you expect the command to be in to your script's $PATH and then just invoke the command without the absolute path. If the command gets moved, well, hopefully it will be to somewhere else on $PATH (as it was in this case), and your script will happily keep working. Better yet, this way your script can work transparently across different Unix environments without having to be changed or conditionalized; just add all of the possible directories to your script's $PATH and be done with it.

(This does point out that the Bourne shell could do with a simple way of adding something to your $PATH if it isn't already there.)

Written on 13 July 2009.
« A brief history of NFS server access restrictions
Some stuff on NFS access restrictions »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Mon Jul 13 00:47:56 2009
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.