I would use the following command (assuming I had GNU
find available):
find $DIR -printf "%T@ %p\n" | sort -n | head -1
The
%T is modification time in a custom format;
@ is the format specifier for for "seconds since the epoch. The rest should be pretty self-evident.
%C would be used if you cared about the "ctime" (the time at which the file's inode was changed in any way, including modifications to the file contents (as with mtime) but also changes to ownership, permissions, link count? etc.
A couple of heuristics for scripting in general:
Any time you're trying to find files with specific characteristics other than matching a simple glob pattern and any of the simple
test features like
-d (directory) or
-r (readable), etc, you almost always want to use the
find command. Most of the switches and arguments to
find control what
find will consider returning (to things like
-print,
-exec, or
-ls).
Any time you're going to compare or manipulate timestamps under UNIX you probably want to use "seconds since the epoch" (this allows simple numeric operations such as sorting or arithmetic adjustment).
So it seems obvious to just traverse the tree printing all the timestamps in a usable form; sort numerically and discard all but the first line. (You could also
sort -nr, reversed, and take the last line with
tail -1; but then your
tail process has to read the entire pipe. In this example the
head command can exit and break the pipe to kill to output from the
sort command; which is marginally more efficient. Of course all of the expense in this is in the
sort command ... it will take most of the CPU time and memory. Meanwhile, of course the
find command will expend I/O -- that's inherent in traversing a filesystem tree).
P.S. If you need to convert a "seconds since the epoch" timestamp into a form you can read you can use an expression like:
date --date "$(( $(date +%s) - $TIMESTAMP )) seconds ago"
.. and naturally you can also specify any format you like for that output as you would with any other
date
JimD (former Linux Gazette AnswerGuy)