Checking whether a program exists

Viewed 2199

In the middle of my perl script I want to execute a bash command. The script takes a long time, so at the beginning of the script I want to see if the command exists. This answer says to just try and run it and this other answer suggests some bash commands to test if the program exists.

Is the latter option the best solution? Are there any better ways to do this check in perl?

4 Answers

What if we assume that we don't know the command's location? This means that syck's answer won't work, and zdim's answer is incomplete.

Try this function in perl:

sub check_exists_command { 
    my $check = `sh -c 'command -v $_[0]'`; 
    return $check;
}
# two examples 
check_exists_command 'pgrep' or die "$0 requires pgrep";
check_exists_command 'readlink' or die "$0 requires readlink";

I just tested it, because I just wrote it.

Related