How would I validate that a program exists? which
would then either return an error and exit or continue with the script.
It seems like it should be easy, but it's been stumping me.
Yes; avoid Why care?
So, don't use
If your hash bang is If your script uses As a simple example, here's a function that runs
In summary:Where When writing a POSIX script, use |
|||||||||||||||||||
|
I agree with lhunath to discourage use of
Command Note: |
|||||||||||
|
It depends whether you want to know whether it exists in one of the directories in the
otherwise use
The redirection to |
|||||
|
To use
This script runs
|
|||||
|
Try using:
or
From the bash manpage under Conditional Expressions:
|
|||||||||
|
To mimic Bash's
|
|||
|
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 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:
|
||||
|
The It returns 0 if the executable is found, 1 if it's not found or not executable:
Nice thing about which is that it figures out if the executable is available in the environment that which is run in - saves a few problems... -Adam |
|||||||
|
I had no success with this solution, I had to modify it a little:
|
|||
|
I had to check if
Hope this help someone else! |
|||||||||
|
The hash-variant has one pitfall: On the command line you can for example type in
to have process executed. For this the parent folder of one_folder must be in $PATH. But when you try to hash this command, it will always succeed:
|
|||
|
|
|||||
|
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 |
|||
|