Has anybody written a bash function to add a directory to $PATH only if it's not already there?
I typically add to PATH using something like:
export PATH=/usr/local/mysql/bin:$PATH
If I construct my PATH in .bash_profile, then it's not read unless the session I'm in is a login session -- which isn't always true. If I construct my PATH in .bashrc, then it runs with each subshell. So if I launch a Terminal window and then run screen and then run a shell script, I get:
$ echo $PATH
/usr/local/mysql/bin:/usr/local/mysql/bin:/usr/local/mysql/bin:....
I'm going to try building a bash function called add_to_path()
which only adds the directory if it's not there. But, if anybody has already written (or found) such a thing, I won't spend the time on it.
Answer
From my .bashrc:
pathadd() {
if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
PATH="${PATH:+"$PATH:"}$1"
fi
}
Note that PATH should already be marked as exported, so reexporting is not needed. This checks whether the directory exists & is a directory before adding it, which you may not care about.
Also, this adds the new directory to the end of the path; to put at the beginning, use PATH="$1${PATH:+":$PATH"}"
instead of the above PATH=
line.
No comments:
Post a Comment