I've encountered a machine that does not have which
. How would you find the path to an executable foo
without which
in a POSIX compliant shell script, if foo
might not even be present?
The code I have does the following:
- if
which
appears available according totype which
exiting 0, then use it - otherwise use
type foo
and depending on whattype
says it is (does the output contain any of the following: keyword, builtin, alias, hash, function), grab the path according to its likely position in the output.
The main problem with this, as @chepner and the man page point out, is type
stdout is in an unspecified format.
My other problem is foo
might not ever exit, so I can't just execute it to see what happens. I want to inspect it first so I need to know where it is.
I feel find / -type f -name foo 2>/dev/null
would take too long. I suppose I could iterate over $PATH
to find it directly. Which approach is best? Iterating over $PATH
or the approach in the two bullets above, or some other approach? I need the solution to be portable.