Skip to content

Commit

Permalink
what: exit(0) only for match
Browse files Browse the repository at this point in the history
* Similar to grep command, exit code 0 means at least one match occurred when looking at input files
* Unlike grep, exit code 1 is shared between no-match and error conditions (e.g. file could not be opened) [1]
* Continue to bail on the 1st open() failure, but now go through exit() instead of die()
* Difference discovered when testing against OpenBSD version

1. https://pubs.opengroup.org/onlinepubs/009696799/utilities/what.html
  • Loading branch information
mknos authored Oct 4, 2024
1 parent 4bda914 commit aeae9d1
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions bin/what
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,22 @@ use strict;

use Getopt::Std qw(getopts);

my $matches = 0;
my %opt;
getopts('s', \%opt) or usage();
@ARGV or usage();

for my $file (@ARGV)
{
open(FILE, '<', $file) or die "Unable to read $file: $!";
printWhat(\*FILE, $file, $opt{'s'});
close FILE;
my $fh;
unless (open $fh, '<', $file) {
warn "Unable to open '$file': $!\n";
last;
}
printWhat($fh, $file, $opt{'s'});
close $fh;
}
exit ($matches ? 0 : 1);

#### read open file and print "what" statements...
#### pass in file handle, file name, and whether to stop printing after 1st "what"
Expand All @@ -38,6 +44,7 @@ sub printWhat
while (defined($line = <$file_handle>))
{
next unless $line =~ m/\@\(#\)/;
$matches++;

if ($line =~ m/\0/) ## there may be more than 1 in here
{
Expand Down Expand Up @@ -68,8 +75,6 @@ sub usage {
Pod::Usage::pod2usage({ -exitval => 1, -verbose => 0 });
}

exit;

__END__
=pod
Expand All @@ -95,6 +100,11 @@ pattern in your file and you are set.
B<->B<s> Stop after the first occurrence of the pattern.
=head1 EXIT STATUS
The what utility exits with status of 0 if any version information was found,
or with a status of 1 otherwise.
=head1 ENVIRONMENT
The working of B<what> is not influenced by any environment variables.
Expand Down

0 comments on commit aeae9d1

Please sign in to comment.