Find the Most Recent File in a Directory on Linux



Linux find statement is one of the most widely used statements that allows us to walk a file hierarchy. It is used to mostly find a specific file or directories and we can also append different other Linux statements or flags along with it to enhance or do a complex operation.

Let’s explore an example of a find statement to understand it better.

In the linux code shown below I am trying to search for a file inside my Downloads folder, and for that I am making use of the find statement.

find sample.sh

Output

sample.sh

Notice that if the find command is able to locate the file then it will simply print the name of the file, if not then it will not return anything the terminal process will terminate.

Now we know how the find statement works, let’s explore the case where we want to use the find command to find the latest file that has been updated in a directory.

Consider a directory named dir1 that contains the following files in it.

immukul@192 dir1 % ls -ltr
total 5232
-rwxrwxrwx 1 immukul staff  446966 Sep 23 1998 wget-1.5.3.tar.gz
drwxrwxrwx 3 immukul staff      96 Jul  7 17:42 d1
-rwxrwxrwx 1 root    staff     106 Jul  8 13:10 sample2.sh
-rwxrwxrwx 1 root    staff     946 Jul 12 18:45 sample.sh
-rwxrwxrwx 1 root    staff     718 Jul 12 18:48 sample1.sh
drwxr-xr-x 2 immukul staff      64 Jul 13 11:36 dr1
drwxr-xr-x 3 immukul staff      96 Jul 13 11:36 dr2
-rw-r--r-- 1 immukul staff     661 Jul 14 09:00 newZip.zip
-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip
-rwxrwxrwx 1 immukul staff      24 Jul 14 15:52 sss.sh
-rw-r--r-- 1 immukul staff     122 Jul 14 16:10 somefile.txt
-rw-r--r-- 1 immukul staff       0 Jul 15 09:44 sample 1.txt
drwxrwxrwx 4 immukul staff     128 Jul 15 10:27 d2

Now since the output of the ls command is not that big, we can manually compare all the times that the files in the above directory were updated on, and get the most recently updated file, but this approach won’t work if we have huge numbers of file as it will be more tedious to go through the times of all the files present in that directory.

A better approach is to make use of the command shown below.

Command

For Mac OS

find . -type f -exec stat -lt "%Y-%m-%d" {} \+ | cut -d' ' -f6- | sort -n | tail -1

For Other Linux Based OS

find . -type f -printf "%T@ %p
" | sort -n | cut -d' ' -f 2- | tail -n 1

Output

2021-07-15 ./sample 1.txt

One alternate way is to make use of the ls command, which looks something like this.

Command

ls -Art | tail -n 1

Output

sample 1.txt
Updated on: 2021-07-29T12:09:37+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements