Skip to content

Commit

Permalink
touch: exit non-zero on failure (#468)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
mknos committed Feb 29, 2024
1 parent 463ca56 commit b7fbd33
Showing 1 changed file with 28 additions and 36 deletions.
64 changes: 28 additions & 36 deletions bin/touch
Expand Up @@ -13,42 +13,27 @@ License: perl


use strict;
use Getopt::Std;

sub parse_time ($);
use File::Basename qw(basename);
use Getopt::Std qw(getopts);

my ($VERSION) = '1.2';

my $warnings = 0;

# Print a usage message on a unknown option.
# Requires my patch to Getopt::Std of 25 Feb 1999.
$SIG {__WARN__} = sub {
require File::Basename;
$0 = File::Basename::basename ($0);
if (substr ($_ [0], 0, 14) eq "Unknown option") {
warn <<EOF;
$0 (Perl bin utils) $VERSION
$0 [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file [files ...]
EOF
exit;
}
else {
$warnings = 1;
warn "$0: @_";
}
};
use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my $Program = basename($0);

$SIG {__DIE__} = sub {
require File::Basename;
$0 = File::Basename::basename ($0);
die "$0: @_";
};
sub parse_time ($);

my ($VERSION) = '1.3';

# Get the options.
getopts ('acmfr:t:', \my %options);
my $rc = EX_SUCCESS;

warn "Unknown option" unless @ARGV;
my %options;
getopts('acmfr:t:', \%options) or usage();
unless (@ARGV) {
warn "$Program: missing file agument\n";
usage();
}

my $access_time = exists $options {a} || !exists $options {m};
my $modification_time = exists $options {m} || !exists $options {a};
Expand Down Expand Up @@ -76,7 +61,8 @@ foreach my $file (@ARGV) {
local *FILE;
require Fcntl; # Import
sysopen FILE, $file, Fcntl::O_CREAT () or do {
warn "$file: $!\n";
warn "$Program: $file: $!\n";
$rc = EX_FAILURE;
next;
};
close FILE;
Expand All @@ -86,21 +72,27 @@ foreach my $file (@ARGV) {
}

my ($aorig, $morig) = (stat $file) [8, 9] or do {
warn "$file: $!\n";
warn "$Program: $file: $!\n";
$rc = EX_FAILURE;
next;
};

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

utime $aset, $mset, $file or do {
warn "$file: $!\n";
warn "$Program: $file: $!\n";
$rc = EX_FAILURE;
next;
};
}
exit $rc;


exit $warnings;
sub usage {
warn "$Program (Perl bin utils) $VERSION\n";
warn "usage: $Program [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file...\n";
exit EX_FAILURE;
}

sub parse_time ($) {
my $time = shift;
Expand Down

0 comments on commit b7fbd33

Please sign in to comment.