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.
There's a ton of options here but I was surprised no quick one-liners, this is what I used at the beginning of my scripts:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; } [[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
this is based on the selected answer here and another source (and me playing around a little).
hope this will be handy for others.
I use this because it's very easy:
or
It uses shell builtin and program echo status to stdout and nothing to stderr by the other hand if a command is not found, it echos status only to stderr.
To use
hash
, as @lhunath suggests, in a bash script:This script runs
hash
and then checks if the exit code of the most recent command, the value stored in$?
, is equal to1
. Ifhash
doesn't findfoo
, the exit code will be1
. Iffoo
is present, the exit code will be0
.&> /dev/null
redirects standard error and standard output fromhash
so that it doesn't appear onscreen andecho >&2
writes the message to standard error.my setup for a debian server. i had a the problem when multiple packages contains the same name. for example apache2. so this was my solution.
I second the use of "command -v". E.g. like this:
Script
Result