From b350935e65bb667479746957faabb0f6fb7fa6a3 Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:32:29 +0800 Subject: [PATCH] head versus tail versus stdin * There's no standards requirement to interpret the argument '-' as stdin [1] * The pod documentation did not mention the '-' argument having a special meaning * Align the code with OpenBSD version: stdin is used if no file arguments are given * head is supposed to be the inverse of tail, and tail doesn't support '-' as stdin * This patch removes functionality; head becomes more consistent with tail 1. https://pubs.opengroup.org/onlinepubs/9699919799/utilities/head.html --- bin/head | 49 ++++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/bin/head b/bin/head index 4a54f84d..9b7a1cf4 100755 --- a/bin/head +++ b/bin/head @@ -43,48 +43,47 @@ if (defined $opt{'n'}) { $count = 10; } -@ARGV = '-' unless @ARGV; -my $err = 0; +my $rc = EX_SUCCESS; my $sep = 0; foreach my $file (@ARGV) { - my ($fh, $is_stdin); - if ($file eq '-') { - $fh = *STDIN; - $is_stdin = 1; - } else { - if (-d $file) { - warn "$Program: '$file' is a directory\n"; - $err++; - next; - } - unless (open $fh, '<', $file) { - warn "$Program: failed to open '$file': $!\n"; - $err++; - next; - } + if (-d $file) { + warn "$Program: '$file' is a directory\n"; + $rc = EX_FAILURE; + next; + } + my $fh; + unless (open $fh, '<', $file) { + warn "$Program: failed to open '$file': $!\n"; + $rc = EX_FAILURE; + next; } - if (scalar(@ARGV) > 1) { - my $fname = $is_stdin ? 'standard input' : $file; if ($sep == 0) { $sep = 1; } else { print "\n"; } - print "==> $fname <==\n"; + print "==> $file <==\n"; + } + tail_fh($fh); + unless (close $fh) { + warn "$Program: failed to close '$file': $!\n"; + $rc = EX_FAILURE; } +} +tail_fh(*STDIN) unless @ARGV; +exit $rc; + +sub tail_fh { + my $fh = shift; + foreach (1 .. $count) { my $line = <$fh>; last unless (defined $line); print $line; } - if (!$is_stdin && !close($fh)) { - warn "$Program: failed to close '$file': $!\n"; - $err++; - } } -exit ($err ? EX_FAILURE : EX_SUCCESS); __END__