Linux: How to delete files and directories older than a number of days
One very common task is to delete files and directories that are older than a number of days, this is what usually we do with backups and…
One very common task is to delete files and directories that are older than a number of days, this is what usually we do with backups and files that their retention period has been expired, lets see how we can do this using the Linux find command.
The primary purpose of the find command is to search for files and directories that match a specific naming pattern or a property, apart from this functionality find can apply specific operations on the found files and directories, in this example we will see how we can delete the files or directories that find returned.
To find all the files and directories that exist under a directory enter find . . If there are files and directories under this directory should return a listing similar to this.
$ find .
.
./c.txt
./b
./b/c.txt
./b/a.txt
./b/b.txt
./a
./a/c.txt
./a/a.txt
./a/b.txt
./c
./c/c.txt
./c/a.txt
./c/b.txt
./a.txt
./b.txtTo find only files we use the -type f option
$ find . -type f
./c.txt
./b/c.txt
./b/a.txt
./b/b.txt
./a/c.txt
./a/a.txt
./a/b.txt
./c/c.txt
./c/a.txt
./c/b.txt
./a.txt
./b.txtTo find only files in the current directory and do not perform a recursive search we use the -maxdepth option
$ find . -maxdepth 1 -type f
./c.txt
./a.txt
./b.txtTo find only files that start with “a” we use the -name option
$ find . -type f -name "a*"
./b/a.txt
./a/a.txt
./c/a.txt
./a.txtAll the above results apply also with the -type d option which searches for directories and not files
$ find . -type d -name "a*"
./aLets try to find files that older than 2 days, “older than two days” means that they have not been modified the last 2 days
$ find . -type f -name "a*" -mtime +2
./b/a.txt
./a/a.txt
./c/a.txtTo delete those files just append the -delete option
$ find . -type f -name "a*" -mtime +2 -deleteNow lets try to find directories not modified the last 2 days
$ find . -type d -mtime +2
./bLike the file delete example we can delete it with the -exec rm -rv {} + -depth options, what it does is that deletes each file in the directory and then the directory each self!
$ find . -type d -mtime +2 -exec rm -rv {} + -depth
removed './b/c.txt'
removed './b/b.txt'
removed directory './b'Conclusion
Find is a powerful command, but as usual what comes with great power comes with great responsibility as well!, a mistaken find command along with a delete operation might cause you major problems like deleting files and directories you need to keep! so be careful and do exhausting testing before applying it to production!.