Detect if PATH has a specific directory entry 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.

Leave a Comment