Skip to content

Commit b7fbd33

Browse files
authored
touch: exit non-zero on failure (#468)
* Exit with non-zero code if usage string is printed * Remove the need for pseudo-signal hanglers * Introduce regular usage() function * test1: bad option -x * test2: no file argument
1 parent 463ca56 commit b7fbd33

File tree

1 file changed

+28
-36
lines changed

1 file changed

+28
-36
lines changed

bin/touch

+28-36
Original file line numberDiff line numberDiff line change
@@ -13,42 +13,27 @@ License: perl
1313

1414

1515
use strict;
16-
use Getopt::Std;
1716

18-
sub parse_time ($);
17+
use File::Basename qw(basename);
18+
use Getopt::Std qw(getopts);
1919

20-
my ($VERSION) = '1.2';
21-
22-
my $warnings = 0;
23-
24-
# Print a usage message on a unknown option.
25-
# Requires my patch to Getopt::Std of 25 Feb 1999.
26-
$SIG {__WARN__} = sub {
27-
require File::Basename;
28-
$0 = File::Basename::basename ($0);
29-
if (substr ($_ [0], 0, 14) eq "Unknown option") {
30-
warn <<EOF;
31-
$0 (Perl bin utils) $VERSION
32-
$0 [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file [files ...]
33-
EOF
34-
exit;
35-
}
36-
else {
37-
$warnings = 1;
38-
warn "$0: @_";
39-
}
40-
};
20+
use constant EX_SUCCESS => 0;
21+
use constant EX_FAILURE => 1;
22+
23+
my $Program = basename($0);
4124

42-
$SIG {__DIE__} = sub {
43-
require File::Basename;
44-
$0 = File::Basename::basename ($0);
45-
die "$0: @_";
46-
};
25+
sub parse_time ($);
26+
27+
my ($VERSION) = '1.3';
4728

48-
# Get the options.
49-
getopts ('acmfr:t:', \my %options);
29+
my $rc = EX_SUCCESS;
5030

51-
warn "Unknown option" unless @ARGV;
31+
my %options;
32+
getopts('acmfr:t:', \%options) or usage();
33+
unless (@ARGV) {
34+
warn "$Program: missing file agument\n";
35+
usage();
36+
}
5237

5338
my $access_time = exists $options {a} || !exists $options {m};
5439
my $modification_time = exists $options {m} || !exists $options {a};
@@ -76,7 +61,8 @@ foreach my $file (@ARGV) {
7661
local *FILE;
7762
require Fcntl; # Import
7863
sysopen FILE, $file, Fcntl::O_CREAT () or do {
79-
warn "$file: $!\n";
64+
warn "$Program: $file: $!\n";
65+
$rc = EX_FAILURE;
8066
next;
8167
};
8268
close FILE;
@@ -86,21 +72,27 @@ foreach my $file (@ARGV) {
8672
}
8773

8874
my ($aorig, $morig) = (stat $file) [8, 9] or do {
89-
warn "$file: $!\n";
75+
warn "$Program: $file: $!\n";
76+
$rc = EX_FAILURE;
9077
next;
9178
};
9279

9380
my $aset = $access_time ? $atime : $aorig;
9481
my $mset = $modification_time ? $mtime : $morig;
9582

9683
utime $aset, $mset, $file or do {
97-
warn "$file: $!\n";
84+
warn "$Program: $file: $!\n";
85+
$rc = EX_FAILURE;
9886
next;
9987
};
10088
}
89+
exit $rc;
10190

102-
103-
exit $warnings;
91+
sub usage {
92+
warn "$Program (Perl bin utils) $VERSION\n";
93+
warn "usage: $Program [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file...\n";
94+
exit EX_FAILURE;
95+
}
10496

10597
sub parse_time ($) {
10698
my $time = shift;

0 commit comments

Comments
 (0)