Detect if user's path has a specific directory in it

Using grep is overkill, and can cause trouble if you're searching for anything that happens to include RE metacharacters. This problem can be solved perfectly well with bash's builtin [[ command:

if [[ ":$PATH:" == *":$HOME/bin:"* ]]; then
  echo "Your path is correctly set"
else
  echo "Your path is missing ~/bin, you might want to add it."
fi

Note that adding colons before both the expansion of $PATH and the path to search for solves the substring match issue; double-quoting the path avoids trouble with metacharacters.


Here's how to do it without grep:

if [[ $PATH == ?(*:)$HOME/bin?(:*) ]]

The key here is to make the colons and wildcards optional using the ?() construct. There shouldn't be any problem with metacharacters in this form, but if you want to include quotes this is where they go:

if [[ "$PATH" == ?(*:)"$HOME/bin"?(:*) ]]

This is another way to do it using the match operator (=~) so the syntax is more like grep's:

if [[ "$PATH" =~ (^|:)"${HOME}/bin"(:|$) ]]

There is absolutely no need to use external utilities like grep for this. Here is what I have been using, which should be portable back to even legacy versions of the Bourne shell.

case :$PATH: # notice colons around the value
  in *:$HOME/bin:*) ;; # do nothing, it's there
     *) echo "$HOME/bin not in $PATH" >&2;;
esac

Tags:

Shell

Bash

Path