Possible Duplicate:
Bash: Detect if user's path has a specific directory in it
Given a directory, how can I determine whether it's on the unix PATH? Looking for a shell script.
Thanks, Kevin
You can write:
if [[ :$PATH: == *:"$directory_you_want_to_check":* ]] ; then
# O.K., the directory is on the path
else
# oops, the directory is not on the path
fi
Note that this won't follow symbolic links, or anything like that; it's just a string comparison, checking if colon-$PATH-colon contains colon-directory-colon.
I usually prefer case
-- posting this in order to make the set complete (-:
case :$PATH: in
*:/home/you/bin:*) ;; # do nothing
*) PATH=/home/you/bin:$PATH ;;
esac
Notice the leading and trailing colons on the case expression in order to simplify the pattern. With case $PATH
you would have to compare to four different patterns, depending on whether the beginning and end of the match was at the beginning or end of the variable.
Quick and dirty: you can echo the (slightly modified) path through grep
and check the return value:
pax> echo ":$PATH:" | grep :/usr/sbin:
:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
pax> echo $?
0
pax> echo ":$PATH:" | grep :/usr/xbin:
pax> echo $?
1
By putting :
at either end of both the path and the directory you're looking for, you simply the grep
expression and ensure only complete paths are found. Otherwise, looking for /usr/bin
may turn up /usr/bin/xyzzy
for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With