Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out external command runability

Tags:

external

raku

How to check whether an external program is available for running via Raku? In shell, type command is to be used, e.g:

if type trash-put
then trash-put delete-me
else rm delete-me
fi

You can't run 'type', 'trash-put' in Raku since type is a shell builtin.
You can, though, run 'sh', '-c', 'type trash-put' or shell 'type trash-put', so Raku equivalent would be:

if ! run( 'sh', '-c', 'type trash-put', :!out ).exitcode {
# if ! shell( 'type trash-put', :!out ).exitcode { # shell alternative to run
  run 'trash-put', 'delete-me';
} else {
  unlink 'delete-me'.IO;
}

but I wonder whether there are any better ways.

The question is not constrained to deleting files, other use-cases need an answer too: prefer curl over wget or browser1 over browser2 or $VISUAL over $EDITOR etc.

like image 364
uxer Avatar asked Aug 10 '21 13:08

uxer


1 Answers

Here is an example using Inline::Perl5 and the can_run() sub routine from the Perl 5 module IPC::Cmd:

use v6;
use IPC::Cmd:from<Perl5> <can_run>;
my $cmd = 'wget';
if (my $exec = can_run($cmd)) {
    say "Path to {$cmd} : $exec";
}
else {
    say "{$cmd} was not found in PATH";
}

Output on my machine:

Path to wget : /bin/wget
like image 187
Håkon Hægland Avatar answered Nov 11 '22 06:11

Håkon Hægland