Find And Delete Files Older Than Some Particular Time Period In Linux

Share

Searching By File Timestamp

Unix/Linux filesystems have three types of timestamp on each file. They are as follows:

  1. Access time (-atime): The timestamp when the file was last accessed.
  2. Modification time (-mtime): The timestamp when the file was last modified.
  3. Change time (-ctime): The timestamp when the metadata for a file (such as permissions or ownership) was last modified.

 

Search and delete file older than 7 days

Lets take an example, wherein we will find and delete file older than 7 days. We will be using the option “-mtime” of the find command for this.

1. Get a list of files using find command as follows:

# find /path_to_directory -mtime +7 -type f -exec ls {}\;

2. If the filenames start with any particular pattern, filter using that as follows:

# find /path_to_directory -name 'filenamepattern*' -mtime +7 -type f -exec ls {}\;

3. After checking and confirming the output, go for removal script(It is very IMPORTANT), otherwise there will be irrecoverable data loss.

# find /path_to_directory -name 'filenamepattern*' -mtime +7 -type f -exec rm -fv {}\;

# find . -name “*.pdf” -atime +7 -exec rm {} \;

4. If this needs to be done on a remote server through cron job and log the filenames of deleted files, use the following command

# ssh user@remote_ip "find /path_to_directory -name 'filenamepattern*' -mtime +7 -type f -exec rm -fv {} \; >> /tmp/backup_deletion`date +%Y%m%d`.log 2>&1"

 

Conclusion

The -mtime parameter will search for files based on the modification time; -ctime searches based on the change time. The -atime, -mtime, and -ctime use time measured in days. The find command also supports options that measure in minutes. These are as follows:

  1. -amin (access time)
  2. -mmin (modification time)
  3. -cmin (change time)

For example, to print all the files that have an access time older than seven minutes, use the following command:

# find . -type f -amin +7 -print

-newer option

The -newer option specifies a reference file with a modification time that will be used to select files modified more recently than the reference file.

Find all the files that were modified more recently than file.txt file:

# find . -type f -newer file.txt -print
Share

Comments

comments

Tags: , , , ,

2 Responses to “Find And Delete Files Older Than Some Particular Time Period In Linux”

  1. immam_DBA says:

    find /u01/appprod/inst/apps/PROD_servername/logs/appl/conc/log/ -type f -name ‘*.req’ -mtime +5 -exec rm -f {} \;

Leave a Reply