Bash – How to find the program I’m hiding in bash

bashpathshellshell-script

Say I have PATH="home/bob/bin:/usr/bin". I am writing a bash script /home/bob/bin/foo that will do some munging and then call /usr/bin/foo. Of course I want to be able to use this script on different systems which have different path structures. In practice the real foo might be in many different places, so I want to just find it from the PATH. My new foo script is on my path too, so I can't just call foo, that will result in a recursive call.

Is there an easy way of doing this in a bash script? (Other than looping through elements of PATH and doing the search manually?)

Best Answer

You can always get the path to the second foo with:

foo=$(type -Pa foo | tail -n+2 | head -n1)

(provided file paths don't contain newline characters).

Beware that may be a relative path which would stop to be valid after you run cd.

You could then do:

hash -p "$foo" foo

So that foo be invoked when you run foo.

Related Question