Reputation: 39
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}
Upvotes: 2
Views: 6125
Reputation: 4334
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
Upvotes: 0
Reputation: 2052
You can give the find -delete
flag to remove the files with it. Just be careful to put it in the end of the command so that the time filter is applied first.
You can first just list the files that the command finds:
find "${M2_REPO}" -depth -mtime +${AGE} -print
The -d
flag makes the find do the search depth-first, which is implied by the -delete
command.
If you like the results, change the print to delete:
find "${M2_REPO}" -mtime +${AGE} -delete
Upvotes: 1
Reputation: 18109
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.
Upvotes: 2