To get the oldest file in a Linux directory, we will use the find and ls command. Let’s get started.
Method 1
In this method, we will use the find command to get the oldest file in the Linux directory. Find command can search for files and directories based on different criteria like search by file name, type, permissions, date of creation, date of modification, etc.
To find the oldest file in a specific directory, you can use the find command as follows:
Let’s break down the command:
- find is the command used to search files in Linux.
- <directory path> is the path to the directory where you want to perform the search operation.
- -type f is used to search for the files only. To search for a directory, use -type d.
- -printf ‘%T+ %p\n’ prints the last modification date & time of file (defined by %T) and file path (defined by %p). The \n adds a new line.
- Sort | head -n 1 it sorts the files numerically and passes its output to the head command which displays the 1 oldest file.
To find the oldest file in the Home directory (~/) of your system, the command would be:
This command will print the oldest file in the Home directory of your system.
To find 3 oldest files in the Home directory, replace 1 by 3:
This command will print 3 oldest files of the specified directory.
As you have seen, the above command only returned the oldest files, not the directories. To display the oldest directory under the specified directory, use -type d instead of -type f as shown below:
For instance, to find the oldest directory under the Home directory (~/) of your system, the command would be:
This command will print the oldest directory located inside your Home directory.
To find 3 oldest directories in the Home directory, replace 1 by 3:
This command will print the 3 oldest directories located inside the Home directory.
Method 2
In this method, we will use the ls command to get the oldest file in a Linux directory. This command’s output includes both files and directories.
To find the oldest file in a specific directory, use either of the below command syntax:
or
If you do not specify the directory path, the command will show the oldest file or subdirectory located inside your current Terminal directory.
To find 3 oldest files in the specified directory, use this command:
or
These commands will show 3 oldest files or directories located inside the specified directory.
That is all there is to it! In this article, we covered how to get the oldest file in the Linux directory through two different methods. Hope you will find this article helpful!