Check if file exists even on PATH

I have something like this:

if(! -e $filename) { # do something } 

but I need to change it so that it looks for the file even on my PATH. Is there a way to achieve this without parsing PATH?

+4
source share
5 answers
+8
source

As you can see, is the file in one of the directories specified in $ENV{PATH} without looking at $ENV{PATH} ? & Hellip; This is a rhetorical question.

Here is a short script I wrote some time ago. You must be able to adapt it for your needs:

 #!/usr/bin/perl use strict; use warnings; use File::Basename; use File::Spec::Functions qw( catfile path ); my $myname = fileparse $0; die "Usage: $myname program_name\n" unless @ARGV; my @path = path; my @pathext = ( q{} ); if ( $^O eq 'MSWin32' ) { push @pathext, map { lc } split /;/, $ENV{PATHEXT}; } PROGRAM: for my $progname ( @ARGV ) { unless ( $progname eq fileparse $progname ) { warn "Not processed: $progname\n\tArgument is not a plain file name\n"; next PROGRAM; } my @results; for my $dir ( @path ) { for my $ext ( @pathext ) { my $f = catfile $dir, "$progname$ext"; push @results, $f if -x $f; } } print "$progname:\n"; print "\t$_\n" for @results; } 
+4
source

The PATH variable is used by the system when loading executable files. Therefore, in order to get the base system to do the work for you, I believe that you will need to try to download the executable. This is not like what you want to do.

Maybe there is a library that offers such functionality, but it’s very simple to write your own. You just need to use split and then repeat.

+3
source

To complement daxim's and Sinan Ünür 's answers :

In limited circumstances, if you do not care if this program is in the system path, you can use the shortcut:

If the target program is a CLI that has an option with no side effects (other than creating the stdout output file), which very quickly terminates the program - for example, --version - you can do the following:

 my $exe = 'bash'; # example `$exe --version` || die "'$exe' not found."; 
0
source

If you want to use the main module, can_run() from IPC :: Cmd .

 use IPC::Cmd qw(can_run); if (can_run($filename)) { # do something } 

Perldoc for File :: What points out a caveat that this will also look for the current directory, even if it is not in your path:

IPC :: Cmd

Comes with the function "can_run" with slightly different semantics, which is traditional UNIX where. It will find executables in the current directory, even if the current default directory is not found on Unix.

0
source

Source: https://habr.com/ru/post/1382709/


All Articles