I use a set of convenience functions for prepending or appending a path to a variable. The functions come in the distribution tarball for Bash in a contrib file called "pathfuncs".
- add_path will add the entry to the end of the PATH variable
- pre_path will add the entry to the beginning of the PATH variable
- del_path will remove the entry from the PATH variable, wherever it is
If you specify a variable as the second argument, it will use that instead of PATH.
For convenience, here they are:
# is $1 missing from $2 (or PATH) ?
no_path() {
eval "case :\$${2-PATH}: in *:$1:*) return 1;; *) return 0;; esac"
}
# if $1 exists and is not in path, append it
add_path () {
[ -d ${1:-.} ] && no_path $* && eval ${2:-PATH}="\$${2:-PATH}:$1"
}
# if $1 exists and is not in path, prepend it
pre_path () {
[ -d ${1:-.} ] && no_path $* && eval ${2:-PATH}="$1:\$${2:-PATH}"
}
# if $1 is in path, remove it
del_path () {
no_path $* || eval ${2:-PATH}=`eval echo :'$'${2:-PATH}: |
sed -e "s;:$1:;:;g" -e "s;^:;;" -e "s;:\$;;"`
}
If you add those to your bash startup file, you can add to your PATH like this:
pre_path $HOME/bin
add_path /sbin
add_path /usr/sbin
Or specify a different variable:
pre_path $HOME/man MANPATH
pre_path $HOME/share/man MANPATH
add_path /usr/local/man MANPATH
add_path /usr/share/man MANPATH
I use this method in my rc files putting the pre_paths first and the add_paths second. It makes all of my path changes easy to understand at a glance. Another benefit is that the lines are short enough that I can add a trailing comment on a line if necessary.
And since these are functions, you can use them interactively from the command line, such as by saying add_path $(pwd)
to add the current directory to the path.
PATH=foo:$PATH
seems wrong because it keep growth every timesource ~/.bashrc
and evenexec bash
can't help since the$PATH
isexport
.