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.
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.
I never did get the above solutions to work on the box I have access to. For one, type has been installed (doing what more does). So the builtin directive is needed. This command works for me:
To mimic Bash's
type -P cmd
we can use POSIX compliantenv -i type cmd 1>/dev/null 2>&1
.If you guys can't get the things above/below to work and pulling hair out of your back, try to run the same command using
bash -c
. Just look at this somnambular delirium, this is what really happening when you run $(sub-command):First. It can give you completely different output.
Second. It can give you no output at all.
I had to check if
git
was installed as part of deploying our CI server. My final bash script was as follows (Ubuntu server):Hope this help someone else!
The following is a portable way to check whether a command exists in
$PATH
and is executable:Example:
The executable check is needed because bash returns a non-executable file if no executable file with that name is found in
$PATH
.Also note that if a non-executable file with the same name as the executable exists earlier in
$PATH
, dash returns the former, even though the latter would be executed. This is a bug and is in violation of the POSIX standard. [Bug report] [Standard]In addition, this will fail if the command you are looking for has been defined as an alias.
command -v works fine if POSIX_BUILTINS option is set for the
<command>
to test for but can fail if not. (it has worked for me for years but recently ran into one where it didn't work).I find the following to be more fail-proof:
Since it tests for 3 things: path, execution and permission.