1. Overview

There are several commands that we can use to get different kinds of information about files and folders in a directory. In this tutorial, we’ll focus on the commands to get information about the most recently updated or modified file in a directory.

2. Setup

Let’s create a sample directory:

$ mkdir sample_directory

Then, we navigate into it and add random files. We’ll create and name the files chronologically to keep track of them:

$ cd sample_directory
$ touch file_1.txt
$ touch file_2.txt
$ touch file_3.txt

We should have this directory structure overall:

$ ls
file_1.txt  file_2.txt  file_3.txt

3. Using find

find is a Linux command to search for files and directories and perform operations on them. It supports searching by file type, folder, name, creation date, modification date, owner, and permissions.

Let’s use this command to display the latest file in our sample directory:

$ find /sample_directory -type f -printf "%t - %p\n" | sort -n | tail -1

Fri Feb 11 05:11:07.8808152360 2022 - sample_directory/file_3.txt

Here’s a breakdown of this command:

  • -type f: locates all files in the directory
  • “%t %p\n”: prints a new line for each file where %t is the file’s last modification time and %p is the filename path. \n creates new lines.
  • sort -n: sorts according to numeric values
  • tail -1: prints the last line

file_3.txt was the last file we created during the setup, which proves the find command works.

Furthermore, we can use find to display several recent files arranged in descending order:

$ find sample_directory/ -type f -exec stat -c '%X %n' {} \; | sort -nr | awk 'NR==1,NR==3 {print $2}'
./file_3.txt
./file_2.txt
./file_1.txt

Here’s a breakdown of the command:

  • -exec stat -c ‘%X %n’: prints the last access time followed by the file path of each file in the working directory
  • sort -nr: sorts in an inverse numerical order
  • awk ‘NR==1,NR==3 {print $2) ‘: prints the second field of the first, second and third lines, which represents the filename in our case. ‘NR’ is a special built-in variable in awk that is used to deal with the number of records present in the files we specify.

We can alter the number of recent files shown by increasing or decreasing the value of 3 in the awk command.

4. Using ls

The ls command lists files or directories in Linux and other Unix-based operating systems. It accepts several flags that allow us to modify how files and folders are listed on the terminal.

We can use ls to view the most recent file through this command:

$ ls sample_directory/ -Artls | tail -1

0 -rw-rw-r-- 1 <user> 0 Thur 11 05:11 file_3.txt

Here’s a breakdown of the command:

  • -A: list all files except those starting with . and ..
  • -r: reverse the order while sorting
  • -t: sort by time, newest first
  • -l: use long list formatting
  • -s: prints allocated size of each file
  • tail -1: prints the last line

Parsing data with ls is error-prone when the filenames contain special characters such as spaces or newlines because the ls command separates filenames with newlines by default.

In the output above, the size of file_3.txt is 0 bytes because it is an empty text file.

Alternatively, we can also use this ls command to get the most recent file:

$ ls -tp | grep -v /$ | head -1
file_3.txt

Here’s a breakdown of this command:

  • -t: sorts by time
  • -p: appends a trailing slash to directories
  • grep -v /$: removes all lines ending in a forward slash
  • head -1: limits the output to a single file. Excluding the -1 suffix will display all files arranged in descending order.

Moreover, we can also display the most recently created or modified files arranged in descending order:

$ ls -tl

total 0
-rw-rw-r-- 1 <user> 0 Thur 11 05:11 file_3.txt
-rw-rw-r-- 1 <user> 0 Thur 11 05:11 file_2.txt
-rw-rw-r-- 1 <user> 0 Thur 11 05:11 file_1.txt

5. Using a Bash Script

A Bash script is a plain text file that contains a series of commands that we would typically have to manually type on the terminal. This can be useful when saving commands that are regularly used or running a chain of commands.

This method is relatively faster than find when performing searches in large directory trees.

Let’s create a recursive Bash script file that’ll retrieve the most recent file.

First, let’s create an executable text file in our working directory:

$ touch bash_script.sh

Next, let’s add the shebang header. This ensures that Bash will be used to interpret the script:

$ echo "#!/bin/bash" >> bash_script.sh

Next, let’s open up the file with the nano editor and paste in this code under the shebang header:

CURRENT_DIR='.'

get_recent_file () {
    FILE=$(ls -Art1 ${CURRENT_DIR} | tail -n 1)
    if [ ! -f ${FILE} ]; then
        CURRENT_DIR="${CURRENT_DIR}/${FILE}"
        get_recent_file
    fi
    echo $FILE
    exit
}
get_recent_file

This function retrieves the most recent item in the directory. If the item is a directory, it’ll navigate into that directory and find the most recent item recursively.

Finally, we need to set the bash_script.sh file as an executable:

$ chmod +x bash_script.sh

We can now execute our script file from the terminal with this command:

$ ./bash_script.sh
bash_script.sh

The output shows bash_script.sh as the most recent file because it’s the last file we updated in the working directory.

6. Using perl

perl is a general-purpose, high-level, interpreted, and dynamic programming language. It was originally developed for text processing and conversion of text files to different formats.

To get the most recent file in our directory, we’ll combine perl with the find command through pipes:

$ find sample_directory/ -type f -printf '%[email protected]\t%p\n' | perl -ane '@[email protected] if ($F[0]>$m[0]); END{print $m[1];}' 

./file_3.txt

Here’s a breakdown of this command:

  • -type f: locates all files in the directory
  • ‘%[email protected]\t%p\n’: prints a new line for each file where %T is the file’s last modification time in a specific format and %p is the file path
  • -ane ‘@[email protected] if ($F[0]>$m[0]); END: each input record is split and stored in an array called @F. It then checks if the value of the first element in the @F array is greater than that in the @m array.
  • {print $m[1];}: prints the second value of @m array, which represents the filename

7. Conclusion

In this article, we’ve covered most of the Linux tools that can be used to get information about the most recently created or updated file. We also looked at how to output more than one recent file arranged in chronological order.

Authors Bottom

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!