Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a directory is on the path in Bash? [duplicate]

Tags:

bash

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

like image 694
Kevin Burke Avatar asked Mar 12 '12 01:03

Kevin Burke


3 Answers

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.

like image 137
ruakh Avatar answered Oct 26 '22 02:10

ruakh


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.

like image 36
tripleee Avatar answered Oct 26 '22 04:10

tripleee


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.

like image 44
paxdiablo Avatar answered Oct 26 '22 02:10

paxdiablo