checking commands in script

IN a lot of shell scripts I write I usually test for the presence of other external commands, that have all to be found and tested like the following:

Code:
PERL_CMD=$( which perl )
if [ -z "$PERL_CMD" ]
then
    # something wrong
fi

I was guessing if, apart from making the above a function, there is some smarter piece of code to search for and test the executable bit of a command by its name.
 
You could write a function that splits the PATH by colons and test each directory for existence and executability of the binary and use the first match. It would be slightly faster than spawning a subshell.
 
The below works without any external processes:
Code:
if ! command -v perl >/dev/null 2>&1; then
    # something wrong
fi

Note that a builtin, function or alias is also considered valid here.
 
While the usage of command(1) is good because it does not open another subshell, I was not looking for a fastest way but a smarter one, that is even using command(1) I have to place the full path in a variable and test if it is not-null (or test the command exit status). So my script will be full of if statements. I think writing a function to clean up the code is therefore the only way to go.
 
Back
Top