How to keep only the last two modified files using shell script?

Siddharth Lakhani
1 min readFeb 14, 2021
Bash Shebang
Bash Shebang

In our routine work of Linux System Administrator, we must have to keep maintain the storage of the Linux Servers so that the system can be served its service adequately.

Here I have introduced a very simple shell script that can be used to keep only the last two modified files in any Linux Server.

This shell script is compatible with all flavors of Linux Distribution.

In this script, the value of variable keep can be set as per our requirement that how many files we want to keep in the server.

The code of this script can also be used in another shell script as one block. For example, if someone running cronjob to take automated back of particular duration and at the end of the process have to make sure that there must be only 2 latest backup available and the rest of them must be deleted. So, this block of code will do the job of deleting the remaining files after completing the backup.

Here is my GitHub repository link for reference.

--

--