Linux Shell Scripting Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

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
Unix does not store file creation time by default; however, some filesystems ( ufs2, ext4, zfs, btrfs, jfs) save the creation time. The creation time can be accessed with the stat command.
Given that some applications modify a file by creating a new file and then deleting the original, the creation date may not be accurate.
The -atime, -mtime, and -ctime option are the time parameter options available with find. They can be specified with integer values in number of days. The number may be prefixed with - or + signs. The - sign implies less than, whereas the + sign implies greater than.

Consider the following example:

  • Print files that were accessed within the last seven days:
        $ find . -type f -atime -7 -print
  • Print files that have an access time exactly seven days old:
        $ find . -type f -atime 7 -print
  • Print files that have an access time older than seven days:
        $ find . -type f -atime +7 -print

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)

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

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

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

The find command's timestamp flags are useful for writing backup and maintenance scripts.