Portably, you'd have to use perl
to gather the timestamps, subtract the amount of time you'd like, then format it for touch
.
t=$(perl make-oldest 1 dir/*)
if [ "$t" -gt 0 ]
then
touch -t "$t" file
else
echo "Sorry, unable to find a file!"
fi
... and the make-oldest perl script is:
#!/usr/bin/perl -w
use strict;
use POSIX qw(strftime);
my $subtract = shift;
my $oldest = 0;
for (@ARGV) {
my @s = stat;
next unless @s;
if ($oldest) {
$oldest = $s[9] if $s[9] < $oldest;
} else {
$oldest = $s[9];
}
}
if ($oldest) {
# convert ($oldest - $subtract) into CCCCYYMMDDhhmm.SS
print strftime "%Y%m%d%H%M.%S\n", localtime($oldest - $subtract);
} else {
print "0\n";
}
The intention is that your shell expands the wildcard dir/*
to get the list of filenames. There are "two" arguments to the perl script: the number of seconds to subtract from the oldest file, and the list of files to gather timestamps from.
The perl script pulls off the subtraction argument then loops over the given files and keeps track of the oldest modification time. If it cannot read any files, then it will return zero (as tested by the wrapper script, above). If an oldest file was found, then we use the strftime
function to convert the subtracted timestamp into the appropriate format for touch
.
stat
to get the mtime of the files in the current directory;sort
to find the smallest mtime value, then shell arithmetic to subtract 1. Usedate
to convert the unix time value to a format suitable fortouch
dir
to consider, or only the files directly in that directory?