There are a few things that it's nice to do when adding a directory path (which hereon I'll refer to as a "dir" to avoid confusion) to PATH:
- Check to see that the dir is actually valid.
- Don't add a dir twice.
- Canonicalize the dir you're adding to ensure you're not adding an alias for an existing dir in
PATH.1 - If a dir is already in
PATHbut not at the front, force it to the front to ensure the programs in that dir take priority over others of the same name in other dirs.
This (Bash-only) function does the above, returns proper error codes, and prints nice messages for humans. (The error codes and messages can be disabled when they're not wanted.)
prepath() {
local usage="\
Usage: prepath [-f] [-n] [-q] DIR
-f Force dir to front of path even if already in path
-n Nonexistent dirs do not return error status
-q Quiet mode"
local tofront=false errcode=1 qecho=echo
while true; do case "$1" in
-f) tofront=true; shift;;
-n) errcode=0; shift;;
-q) qecho=':'; shift;;
*) break;;
esac; done
# Bad params always produce message and error code
[[ -z $1 ]] && { echo 1>&2 "$usage"; return 1; }
[[ -d $1 ]] || { $qecho 1>&2 "$1 is not a directory."; return $errcode; }
dir="$(command cd "$1"; pwd -P)"
if [[ :$PATH: =~ :$dir: ]]; then
$tofront || { $qecho 1>&2 "$dir already in path."; return 0; }
PATH="${PATH#$dir:}" # remove if at start
PATH="${PATH%:$dir}" # remove if at end
PATH="${PATH//:$dir:/:}" # remove if in middle
fi
PATH="$dir:$PATH"
}
1 Technically, you also should be canonicalizing all existing directories in PATH, but I've been too lazy to do that in the code included here.