I'm looking for a shell one-liner to find the oldest file in a directory tree.
Although the accepted answer and others here do the job, if you have a very large tree, all of them will sort the whole bunch of files.
Better would be if we could just list them and keep track of the oldest, without the need to sort at all.
Thats why I came up with this alternative solution:
I hope it might be of any help, even if the question is a bit old.
Edit 1: this changes allow parsing files and directories with spaces. Its is fast enough to issue it in the root
EDIT 2: Same concept, better solution using
Please use ls - the man page tells you how to order the directory.
The -n 2 is so you dont get the "total" in the output. If you only want the name of the file.
And if you need the list in the normal order (getting the newest file)
Much easier than using find, much faster, and more robust - dont have to worry about file naming formats. It should work on nearly all systems too.
This works (updated to incorporate Daniel Andersson's suggestion):
The following commands commands are guaranteed to work with any kind of strange file names:
Using a null byte (
The commands are ordered by execution time (measured on my machine).
This one's a little more portable and because it doesn't rely on the GNU
The only downside here is that it's somewhat limited to the size of
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
protected by Community♦ Jun 8 at 14:14
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?