patternbashModerate
Unix shell function for adding directories to PATH
Viewed 0 times
pathunixfunctionaddingshellfordirectories
Problem
Adding a directory to the
Here's what I have (syntax is in
This function works. I have tested it on Ubuntu, Solaris, and FreeBSD. And I have tested it in
Remarks
PATH in Unix/Linux is a very common task. However, what if the directory is already in the path? My goal is to write a shell function (preferably portable) that will add a directory to the front or back of the PATH variable, but only if it's not already there.Here's what I have (syntax is in
zsh / bash):#-------
# DESC: Adds a directory to the PATH if it's not already in the PATH
# ARGS:
# 1 - The directory to add
# 2 - Which end of PATH to add to. Use "front" to prepend.
#-------
add2path() {
if ! echo $PATH | egrep "(^|:)$1(:|\$)" > /dev/null ; then
if [[ $2 = "front" ]]; then
PATH="$1:$PATH"
else
PATH="$PATH:$1"
fi
export PATH
fi
}This function works. I have tested it on Ubuntu, Solaris, and FreeBSD. And I have tested it in
bash, zsh, and ksh. But I want to make sure that it is as portable (first and foremost), readable, and as efficient as possible.Remarks
- I know that the
=~operator would be more readable, but I had trouble with it not working on certain OSes, particularly Solaris.
- I know I could (and arguably should) use
grep -Fqinstead ofegreprouting to/dev/null, but again this didn't work on certain OSes (Solaris)
- Ironically, the way to fix this on Solaris is to add
/usr/xpg4/binto the PATH. :)
Solution
grep is most likely an overkill. After setting IFS=":", the $PATH is conveniently split into words. Then the presence of the directory can be determined in a simple loopIFS=":"
for pathdir in $PATH; do
if [ $pathdir == $1]; then return; fi
done
# Now restore IFS and modify path as needed.Code Snippets
IFS=":"
for pathdir in $PATH; do
if [ $pathdir == $1]; then return; fi
done
# Now restore IFS and modify path as needed.Context
StackExchange Code Review Q#88236, answer score: 10
Revisions (0)
No revisions yet.