Last updated on April 19th, 2018 at 07:48 am
INTRODUCTION
How to Delete Files Older Than X Number of Days in Linux
After reading our old article on Linux Backup, many readers asking how to keep limited amount of backup files or how to delete backup files older than x number of days so now I am writing this guide in response to our readers question,
Queries from the readers:
SOLUTION
Using find utility we can easily figure out files older than x number of days and then use the rm command to delete them.
Here is combination of find and rm command to find and delete older files using some interesting arguments.
1- Find All Files Inside Directory and Delete Files which is Older Than 10 Days
find /location/to/find/files/* -mtime +10 -exec rm {} \;
Command Explanation:
1- find /location/to/find/files/*
This command use to find files in Linux operating system. Next part of this command is /locatin/to/find/files/ which means find files inside this directory suppose I have directory on root named backup so my command will be find /backup/*.
2- mtime +10
The next argument -mtime, is used to specify the number of days. In our example we uses -mtime +10 so it will find files older than 10 days.
3- -exec rm {} \;
The last argument contains two parts, “–exec” allows you to pass an other command such as rm, and the second part “{} \;” is required to end the command.
2- Delete Files which is Older Than 5 Days With .tar File Extension.
find /backup -name "*.tar" -type f -mtime +5 -exec rm -fr {} \;
Very Important: Be VERY careful to supply an absolute path while using “rm” commands!.
3- Find and Delete Files using Find Command.
Same task you can perform using find command only. See below example:
find /location/to/find/files/* -mtime +10 -type f -delete
Tip:- you can add this command in bash script and automate this process using cron job utility.
I want to ZIP the file in the same directory, if its older than 7 days. This has to be performed in all folders of my unix box. Thanks in advance.
Thank you
Am I right to write find comments in the script files such as filename.sh??
Hi, can i use this bash script? auto backup folder and delete tar files older than 7 days.
#!/bin/bash
#Purpose = Backup of Important Data
#Created on 17-1-2012
#Author = Hafiz Haider
#Version 1.0
#START
TIME=`date +%b-%d-%y` # This Command will add date in Backup File Name.
FILENAME=backup-$TIME.tar.gz # Here i define Backup file name format.
SRCDIR=/imp-data # Location of Important Data Directory (Source of backup).
DESDIR=/mybackupfolder # Destination of backup file.
tar -cpzf $DESDIR/$FILENAME $SRCDIR
find /mybackupfolder -name “*.tar” -type f -mtime +7 -exec rm -fr {} \;
#END