Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a program exists

Tags:

linux

bash

perl

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?

like image 706
flakes Avatar asked Jan 06 '23 12:01

flakes


2 Answers

My best guess is that you want to check for existence of an executable file that you want to run using system or qx//

But if you want your command line to behave the same way as the shell, then you can probably use File::Which

like image 94
Borodin Avatar answered Jan 15 '23 03:01

Borodin


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.

like image 26
marinara Avatar answered Jan 15 '23 03:01

marinara