It is always recommended to find and cleanup your old files which are no longer necessary after a certain period of time. This will save you some disk space. If you didn't clean your old files yet, here is a quick way to do that. This brief tutorial walk you through how to find and delete files older than X days in Linux and Unix-like operating systems.
Disclaimer:
You should be extremely careful while running the following commands. These commands will not ask you any confirmation before deleting the files. It will simply delete the files once you hit the ENTER key. So be very careful and double check the files you're about to delete.
Find And Delete Files Older Than X days In Linux
First, let us find out the files older than X days, for example 30 days.
To do, so, just run:
$ find . -mtime +30 -print
The above command will find and display the older files which are older than 30 day in the current working directory.
Here,
dot (.)
- Indicates the current directory.-mtime
- Indicates the file modification time and is used to find files older than 30 days.-print
- Displays the older files
If you want to search files in a specific directory, just replace the dot with the folder path.
For example, to find out the files which are older than 30 days in /home/sk/Downloads
directory, just run:
$ find /home/sk/Downloads -mtime +30 -print
Sample Output:
/home/sk/Pictures/Wallpapers /home/sk/Pictures/Wallpapers/29312450971_819c502b2e_o.jpg /home/sk/Pictures/Wallpapers/skamath-HD-Wallpapers1.jpg /home/sk/Pictures/Deepin Movie /home/sk/Pictures/smplayer_screenshots
Now, run any one of the following command to delete the files which are not required anymore. Again, I warn you that these commands will delete the files immediately once you hit ENTER button. Please be cautious and double check before running these commands.
$ find <Path_To_Old_Files> -type f -mtime +30 | xargs rm -f
Or,
$ find <Path_To_Old_Files> -mtime +30 -exec rm -f {} \;
Or,
$ find <Path_To_Old_Files> -mtime +30 -delete;
Conclusion
This is how I find and remove files older than certain period of time in my Linux servers. Delete old files periodically if they are not necessary at regular intervals, or backup them to any external drives and free up disk space. You can use the free space for any other useful purposes.
2 comments
You might to try tmpwatch
I prefer “find -ctime +30 -delete” over, sending it to exec, not sure if its specific to RHEL and CentOS 7 but it works fine in my testing.