How to find the latest file on Unix or Linux (recursive)

Hi all,

I need to get the latest file. I have found this command "ls -lrt" that is great but not recursive.

Can anyone help?

Thanx by advance.

find

Could you please be more explicit, how do I get the sorting by date?

This will give you the latest file under $basedir, recursively :

while read F; do stat "$F" -c'%Y %n'; done < <(find "$basedir" -mtime 1)|sort|cut -d' ' -f2-|tail -1

Note that it will work only for files modified in the last 24 hours, you can change the mtime parameter to higher if needed.
Maybe there's a simpler way...

I have finally found. The following command find the latest file, including the handling of filename with spaces.

find . -type f -printf %p";" | xargs -d ";" ls -t | head -1

So long as xargs only invokes ls once.

---------- Post updated at 05:43 PM ---------- Previous update was at 05:36 PM ----------

I don't think there's any need for that while loop. You should be able to get it done using find's exec primary.

find "$basedir" -mtime 1 -exec stat -c '%Y %n' {} + | sort ....

Save yourself a few calls to stat as well.

Also, if you reverse the sort order, you can use head and finish faster (no need to pipe everything through cut and tail).

Regards,
Alister

Thanks for that. I'll have to study better the specific syntax of find, i read some things about but didn't have the need of them. That's why i proposed such a dirty solution. :rolleyes:

I just took a look at a gnu find man page online. If gnu find is acceptable, there's no need to use "-exec stat ...". -printf can be used instead.

Regards,
Alister