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 on nullglob for that glob. So if there's no file in the directory, expands to nothing causing perl's -M to return undef.
    • -: causes next glob qualifiers to apply on the target of symlinks
    • Om: reverse (capital) order by modification time (so from oldest to newest like ls -rt)
    • [1]: select first matching file only
  • -M file: gets the age of the content of the file.
  • 0+ or 86400* force a conversion to number (for the undef 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 variable d
    • BEGIN {m=d} initialize m to d
    • $0 < m {m = $0} keeping track of the minimum in m
    • END {print d - m} print the difference.