How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?
It seems like it should be easy, but it’s been stumping me.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Answer
POSIX compatible:
Example use:
For Bash specific environments:
Explanation
Avoid
which. Not only is it an external process you’re launching for doing very little (meaning builtins likehash,typeorcommandare way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.Why care?
whichthat doesn’t even set an exit status, meaning theif which foowon’t even work there and will always report thatfooexists, even if it doesn’t (note that some POSIX shells appear to do this forhashtoo).whichdo custom and evil stuff like change the output or even hook into the package manager.So, don’t use
which. Instead use one of these:(Minor side-note: some will suggest
2>&-is the same2>/dev/nullbut shorter – this is untrue.2>&-closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))If your hash bang is
/bin/shthen you should care about what POSIX says.typeandhash‘s exit codes aren’t terribly well defined by POSIX, andhashis seen to exit successfully when the command doesn’t exist (haven’t seen this withtypeyet).command‘s exit status is well defined by POSIX, so that one is probably the safest to use.If your script uses
bashthough, POSIX rules don’t really matter anymore and bothtypeandhashbecome perfectly safe to use.typenow has a-Pto search just thePATHandhashhas the side-effect that the command’s location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.As a simple example, here’s a function that runs
gdateif it exists, otherwisedate:Alternative with a complete feature set
You can use scripts-common to reach your need.
To check if something is installed, you can do: