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.
Expanding on @lhunath's and @GregV's answers, here's the code for the people who want to easily put that check inside an
if
statement:Here's how to use it:
If you check for program existence, you are probably going to run it later anyway. Why not try to run it in the first place?
It's a more trustworthy check that the program runs than merely looking at PATH directories and file permissions.
Plus you can get some useful result from your program, such as its version.
Of course the drawbacks are that some programs can be heavy to start and some don't have a
--version
option to immediately (and successfully) exit.Check for multiple dependencies and inform status to end users
Sample output:
Adjust the
10
to the maximum command length. Not automatic because I don't see a non verbose POSIX way to do it: How to align the columns of a space separated table in Bash?For those interested, none of the methodologies above work if you wish to detect an installed library. I imagine you are left either with physically checking the path (potentially for header files and such), or something like this (if you are on a Debian-based distro):
As you can see from the above, a "0" answer from the query means the package is not installed. This is a function of "grep" - a "0" means a match was found, a "1" means no match was found.
I have a function defined in my .bashrc that makes this easier.
Here's an example of how it's used (from my
.bash_profile
.)I'd say there's no portable and 100% reliable way due to dangling
alias
es. For example:Of course only the last one is problematic (no offence to Ringo!) But all of them are valid
alias
es from the point of view ofcommand -v
.In order to reject dangling ones like
ringo
, we have to parse the output of the shell built-inalias
command and recurse into them (command -v
is no superior toalias
here.) There's no portable solution for it, and even a Bash-specific solution is rather tedious.Note that solution like this will unconditionally reject
alias ls='ls -F'