How to test whether PATH has a specific directory in it in Bash on Linux?
Posted on In QAHow to test whether PATH has a specific directory in it in Bash on Linux?
For example, how to test whether /usr/local/mytool/bin
is in $PATH
?
Directories in the $PATH
variable are separated by :
. So you can use a regular expression to test whether the $PATH
contains a directory.
The code for your specific example will be as follows (print true or false).
if [[ "$PATH" =~ (^|:)"/usr/local/mytool/bin"(|/)(:|$) ]]; then
echo true
else
echo false
fi
Explanations:
There are several corner cases handled:
The path is the first directory in $PATH
. So (^|:)
at the beginning of the regex.
The path is the last directory in $PATH
. So (:|$)
at the end of the regex.
The path can have a trailing ‘/’ or not. So (|/)
after the path.
Of course, there are still other wired cases. But they are not handled here.