How to check if a directory is on a path in Bash?

Possible duplicate:
Bash: Determine if user path has a specific directory

Given a directory, how can I tell if it's on the unix PATH? Search for a shell script.

Thanks, Kevin

+3


source to share


5 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 the colon-PATH-colon contains a colon-colon.

+18


source


Quick and dirty: you can echo a (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 placing :

at either end of both the path and the directory you are looking for, you are just an expression grep

and make sure that only full paths are found. Otherwise, the search /usr/bin

might look like, for example /usr/bin/xyzzy

.

+4


source


I usually prefer case

- to post this to make the set complete (-:

case :$PATH: in
  *:/home/you/bin:*)  ;;  # do nothing
  *) PATH=/home/you/bin:$PATH ;;
esac

      

Note the leading and trailing colons in the case statement to simplify the pattern. With help, case $PATH

you will have to compare against four different patterns depending on whether the start and end of the match was at the start or end of a variable.

+3


source


I will probably have something like this, i.e. echo existing $ PATH and grep for the pattern.

#!/bin/sh

if [ $# -ne 1 ]; then
 echo "$0 <dir>"
 exit 1
fi 

dir=${1%/};

if [ `echo :$PATH: | grep -F :$dir:` ]; then
   echo "$dir is in the UNIX path"
else
   echo "$dir is not in the UNIX path"
fi

      

0


source


Maybe this can help:

#!/bin/bash

DIR="/usr/xbin"
[ `echo ":$PATH:" | grep :$DIR:` ] && echo true || echo false

      

-1


source







All Articles