How to test whether PATH has a specific directory in it in Bash on Linux?

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 $PATH?

asked Apr 6, 2016 by anonymous

1 Answer

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.

answered May 3, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...