With /bin/bash
, how would I detect if a user has a specific directory in their $PATH variable?
For example
if [ -p \"$HOME/bin\" ]; then
$PATH
is a list of strings separated by :
that describe a list of directories. A directory is a list of strings separated by /
. Two different strings may point to the same directory (like $HOME
and ~
, or /usr/local/bin
and /usr/local/bin/
). So we must fix the rules of what we want to compare/check. I suggest to compare/check the whole strings, and not physical directories, but remove duplicate and trailing /
.
First remove duplicate and trailing /
from $PATH
:
echo $PATH | tr -s / | sed 's/\/:/:/g;s/:/\n/g'
Now suppose $d
contains the directory you want to check. Then pipe the previous command to check $d
in $PATH
.
echo $PATH | tr -s / | sed 's/\/:/:/g;s/:/\n/g' | grep -q "^$d$" || echo "missing $d"
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"(:|$) ]]