Possible Duplicate:
Find out if a command exists on POSIX system
How to find a usable executable file in bash
On the command line I'd type (e.g.) type vimdiff
(or which vimdiff
if type
is not available on the machine). But in a script, what is the most reliable way to check for a utility and then take some action depending on its availability.
The purpose at hand, if it helps to know, is I'm writing a function, thediff
, which I can install on local and remote machines of various operating system and various flavors of OS, and let it pass arguments off to p4merge if it's available (for OS X and Windows/Cygwin environments), and if not then try vimdiff
and use that if it's available, and if not then default to diff
with my preferred options (e.g. --side-by-side --suppress-common-lines --ignore-space-change
').
Since which
is notoriously unreliable in the form of feedback it gives, I'm not sure if I can count on $?
being 1
if the utility in question is not installed. But on the other hand, I'm not sure I can rely on type
being installed at all.
It seems kludgey, but what about just trying the first utility, and if $?
is non-zero then trying the next, etc.
How is this generally handled?
UPDATE:
Although I did tag this with 'bash', that was only to get the attention of people following the bash tag, since they'd be likely to know an answer. I did not mean to imply that I only ever use bash, or that I can assume bash will be present on all systems I use. In fact I've had to work on systems where grumpy sysadmins made it difficult to use anything but the Korn shell. And (whenever available) I use zsh instead of bash. So this is not an exact duplicate of How to find a usable executable file in bash since that requires bash. So the questions are different. Further, I explicitly stated that I've had to use systems where type
is not available. All the closers apparently overlooked that fact.
This question might legitimately be a duplicate of the other question, if all the systems I mentioned are in fact POSIX compliant. I don't know whether they are.