I'm currently using ls -t | head -1 to get the name of the newest file. But it takes a long time because my directory has a million files. I guess a chunk of time is lost unnecessarily in ls -t when it outputs the list of the million files, all except the first are going to be rejected anyway.

Is there any quicker way? For example, some way to directly tell ls to output only the first line?

  • 2
    I would guess the time it takes is mostly spent in the sorting... – m4573r May 20 '14 at 11:48
  • how frequently new files are being added ? – kmonsoor May 26 '14 at 1:52

I bet all of the time is spent comparing the files' creation dates: though not really proportional to N^2 (it really goes like N log N for smart sorting algorithms), this is still quite long.

The following command

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

finds all files in the current directory, lists them from newest to oldest, then prints only the first item.

It can be conveniently modified for instance as follows:

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

This commands finds only files created in the last day (-mtime -1), and sorts only these. Hopefully, this should be enough to restrict the search to a small number of items.

if you need a finer control, you can use:

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

which, for instance, selects only files created/modified less than 5 minutes ago (-mmin -5).

This way, the ordering is restricted to a manageable number of objects. If necessary, the command can be conveniently aliased, or scripted, for typing convenience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.