Skip to content

Commit

Permalink
which: 3 distinct exit codes (#486)
Browse files Browse the repository at this point in the history
* which: 3 distinct exit codes

* Previously, bin/which would use exit code 0 (success) even if it failed to locate a command, making it more difficult to use in shell scripts
* Follow GNU version and treat exit code 2 as internal error, 1 as partial-or-no-match, 0 as all-commands-matched
* Follow OpenBSD version and print error to stderr for each command that does not match
* Bump version
* test1: "perl which" --> invalid usage due to no argument, exit(2)
* test2: "perl which sh ls" --> sh and ls are both found on my system, exit(0)
* test3: "perl which sh brash" --> sh is found and brash is not, exit(1)

* previous commit didn't handle -a flag
  • Loading branch information
mknos committed Mar 7, 2024
1 parent edc276a commit 969bf61
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions bin/which
Expand Up @@ -17,10 +17,11 @@ use File::Basename qw(basename);
use Getopt::Std qw(getopts);

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;
use constant EX_PARTIAL => 1;
use constant EX_FAILURE => 2;

my $Program = basename($0);
my ($VERSION) = '1.3';
my ($VERSION) = '1.4';

sub usage {
warn "$Program version $VERSION\n";
Expand Down Expand Up @@ -82,12 +83,16 @@ if (defined($ENV{PATHEXT})) {
}
if ($^O eq 'VMS') { @PATHEXT = qw(.exe .com); }

my $rc = EX_SUCCESS;

COMMAND:
foreach my $command (@ARGV) {
my $found = 0;
if ($^O eq 'VMS') {
my $symbol = `SHOW SYMBOL $command`; # line feed returned
if (!$?) {
print "$symbol";
$found = 1;
next COMMAND unless $opt{'a'};
}
}
Expand All @@ -97,10 +102,12 @@ foreach my $command (@ARGV) {
if (lc($alias) eq lc($command)) {
# MPW-Perl cannot resolve using `Alias $alias`
print "Alias $alias\n";
$found = 1;
next COMMAND unless $opt{'a'};
}
}
}
next COMMAND if $found;

foreach my $dir (@PATH) {
my $path = $dir . $file_sep . $command;
Expand All @@ -111,12 +118,14 @@ foreach my $command (@ARGV) {
if ($^O eq 'MacOS') {
if (-e $path) {
print "$path\n";
$found = 1;
next COMMAND unless $opt{'a'};
}
}
else {
if (-x $path) {
print "$path\n";
$found = 1;
next COMMAND unless $opt{'a'};
}
}
Expand All @@ -127,11 +136,16 @@ foreach my $command (@ARGV) {
}
if (-x $pathext) {
print "$pathext\n";
$found = 1;
next COMMAND unless $opt{'a'};
}
}
}
next COMMAND if $found;
warn "$Program: $command: command not found\n";
$rc = EX_PARTIAL;
}
exit $rc;

__END__
Expand Down

0 comments on commit 969bf61

Please sign in to comment.