Searching by file timestamp
Unix/Linux filesystems have three types of timestamp on each file. They are as follows:
- Access time (-atime): The timestamp when the file was last accessed.
- Modification time (-mtime): The timestamp when the file was last modified.
- 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 {}\;
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:
- -amin (access time)
- -mmin (modification time)
- -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