And they said it couldn't be done...

Script to manage the Unix $PATH variable

They said it could not be done. Scripts cannot modify environment variables because they run in a subshell, so any changes made are lost when the subshell returns.

Well, that's not quite true. A script can return a result string, which the statement that calls the script can use in a setenv statement.

What makes this practical is to put the calling mess into an alias.

alias path 'setenv PATH `$HOME/src/script/closure/path "\!*:q"`'

The magic at the end of the command only works in the C shell. Not in the tcsh. Not in the bash? Dunno, don't remember. Might or might not have gotten it working under Linux.

The path script can be called to
path Display the current value of $PATH
path + <dir> Add <dir> to (the end of) the current path
path - <dir> Remove <dir> from (anywhere in) the current path

The real magic is to catch EVERY error condition and return the current value of the path. If this is not done, an error can cause the path to be reset to nothing, which makes for a not-very-sane Unix experience from there on in.

Oh, and make sure to redirect diagnostic output to STDERR so you see it instead of it going into the new $PATH value.


Back to ZBEN's home page.