Wednesday, January 4, 2012

How to delete files older than certain time in linux

The find utility on linux allows us to pass in a bunch of interesting arguments, including one to execute another command on each file. We’ll use this in order to figure out what files are older than a certain time/days, and then use the rm or delete command to delete them.

Using rm command


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.


Using delete command

First goto the Directory where we have to delete the files older than certain time/day.
CD /directory/path

Now Suppose we have to delete files older than 2 hour so we will use -mmin +120 which will list out all files older than 2 hours(120 min) & then delete to delete them as

Find . -mmin +120 -delete

Now Suppose we have to delete files older than 2 day so we will use -mtime +2 which will list out all files older than 2 days  & then delete to delete them as

Find . -mtime +2 -delete

here i am using  '.' after find which is showing current directory.

 

No comments:

Post a Comment