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\
In case you want to check if a program exists and is really a program, not a Bash built-in command, then command
, type
and hash
are not appropriate for testing as they all return 0 exit status for built-in commands.
For example, there is the time program which offers more features than the time built-in command. To check if the program exists, I would suggest using which
as in the following example:
# First check if the time program exists
timeProg=`which time`
if [ "$timeProg" = "" ]
then
echo "The time program does not exist on this system."
exit 1
fi
# Invoke the time program
$timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
echo "Total CPU time: `dc -f result.txt` seconds"
rm result.txt