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

Posted on In QA

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?

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.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *