'How to delete files and directories older than n days in linux
I have a directory named repository which has a number of files and sub directories. I want to find the files and directories which have not been modified since last 14 days so that I can delete those files and directories. I have wrote this script but it is giving the directory name only
#!/bin/sh
M2_REPO=/var/lib/jenkins/.m2/repository
echo $M2_REPO
OLDFILES=/var/lib/jenkins/.m2/repository/deleted_artifacts.txt
AGE=14
find "${M2_REPO}" -name '*' -atime +${AGE} -exec dirname {} \; >> ${OLDFILES}
Solution 1:[1]
find /path/to/files* -mtime +5 -exec rm {} \;
Note that there are spaces between rm, {}, and \;
Explanation
The first argument is the path to the files. This can be a path, a directory, or a wildcard as in the example above. I would recommend using the full path, and make sure that you run the command without the exec rm to make sure you are getting the right results.
The second argument, -mtime, is used to specify the number of days old that the file is. If you enter +5, it will find files older than 5 days.
The third argument, -exec, allows you to pass in a command such as rm. The {} \; at the end is required to end the command.
This should work on Ubuntu, Suse, Redhat, or pretty much any version of linux.
Solution 2:[2]
I know this is a very old question but FWIW I solved the problem in two steps, first find and delete files older than N days, then find and delete empty directories. I tried doing both in one step but the delete operation updates the modification time on the file's parent directory, and then the (empty) directory does not match the -mtime
criteria any more! Here's the solution with shell variables:
age=14
dir="/tmp/dirty"
find "$dir" -mtime "+$age" -delete && find "$dir" -type d -empty -delete
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Martin G |
Solution 2 | chrisinmtown |