How 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
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
There are several corner cases handled:
The path is the first directory in
(^|:) at the beginning of the regex.
The path is the last directory in
(:|$) 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.