Find the age of the oldest file in one line or return zero
With zsh
and perl
:
perl -le 'print 0+-M $ARGV[0]' /path/to/dir/*(N-Om[1])
(add the D
glob qualifier if you also want to consider hidden files (but not .
nor ..
)).
Note that for symlinks, that considers the modification time of the file it resolves to. Remove the -
in the glob qualifiers to consider the modification time of the symlink instead (and use (lstat$ARGV[0] && -M _)
in perl
to get the age of the symlink).
That gives the age in days. Multiply by 86400 to get a number of seconds:
perl -le 'print 86400*-M $ARGV[0]' /path/to/dir/*(N-Om[1])
(N-Om[1])
: glob qualifier:N
: turns onnullglob
for that glob. So if there's no file in the directory, expands to nothing causingperl
's-M
to returnundef
.-
: causes next glob qualifiers to apply on the target of symlinksOm
: reverse (capital) order by modification time (so from oldest to newest likels -rt
)[1]
: select first matching file only
-M file
: gets the age of the content of the file.0+
or86400*
force a conversion to number (for theundef
case).
If it must be one line:
stat -c %Y ./* 2>/dev/null | awk -v d="$(date +%s)" 'BEGIN {m=d} $0 < m {m = $0} END {print d - m}'
stat -c %Y ./* 2>/dev/null
print the timestamp of all files, ignoring errors (so no files results in no output)With awk:
-v d="$(date +%s)"
save the current timestamp in a variabled
BEGIN {m=d}
initializem
tod
$0 < m {m = $0}
keeping track of the minimum inm
END {print d - m}
print the difference.