How can I find the oldest file in a directory tree

This works (updated to incorporate Daniel Andersson's suggestion):

find -type f -printf '%T+ %p\n' | sort | head -n 1

This one's a little more portable and because it doesn't rely on the GNU find extension -printf, so it works on BSD / OS X as well:

find . -type f -print0 | xargs -0 ls -ltr | head -n 1

The only downside here is that it's somewhat limited to the size of ARG_MAX (which should be irrelevant for most newer kernels). So, if there are more than getconf ARG_MAX characters returned (262,144 on my system), it doesn't give you the correct result. It's also not POSIX-compliant because -print0 and xargs -0 isn't.

Some more solutions to this problem are outlined here: How can I find the latest (newest, earliest, oldest) file in a directory? – Greg's Wiki


The following commands commands are guaranteed to work with any kind of strange file names:

find -type f -printf "%T+ %p\0" | sort -z | grep -zom 1 ".*" | cat

find -type f -printf "%T@ %T+ %p\0" | \
    sort -nz | grep -zom 1 ".*" | sed 's/[^ ]* //'

stat -c "%y %n" "$(find -type f -printf "%T@ %p\0" | \
    sort -nz | grep -zom 1 ".*" | sed 's/[^ ]* //')"

Using a null byte (\0) instead of a linefeed character (\n) makes sure the output of find will still be understandable in case one of the file names contains a linefeed character.

The -z switch makes both sort and grep interpret only null bytes as end-of-line characters. Since there's no such switch for head, we use grep -m 1 instead (only one occurrence).

The commands are ordered by execution time (measured on my machine).

  • The first command will be the slowest since it has to convert every file's mtime into a human readable format first and then sort those strings. Piping to cat avoids coloring the output.

  • The second command is slightly faster. While it still performs the date conversion, numerically sorting (sort -n) the seconds elapsed since Unix epoch is a little quicker. sed deletes the seconds since Unix epoch.

  • The last command does no conversion at all and should be significantly faster than the first two. The find command itself will not display the mtime of the oldest file, so stat is needed.

Related man pages: find – grep – sed – sort – stat

Tags:

Linux

Unix

Shell