Search code examples
linuxcommand-linefilesystemsrmsystem-administration

Deleting files after 7 days not working


I am trying to delete all files that are older than 7 days. The command is working but not correctly.

 find '/files/tem_data/' -mtime +7 -exec rm -rf {} \+

It does delete files but it's not accurate.

ls -Artl | head -n 2

The find does delete files, but when I run the ls command does contain files that should be deleted. For example today is November 7th. The find should delete all files before November 1st. It does not. The command leaves files that are in October 30 and 31. How can I delete files that are older than 7 days.

If I run find command like 3 minutes later. It deletes files with the date of October 30 and a time of 3 minutes after it first ran.


Solution

  • From man find:

    -atime n
    
      File  was  last  accessed  n*24  hours  ago.  When find figures out how many
      24-hour periods ago the file was  last  accessed,  any  fractional  part  is
      ignored,  so  to  match -atime +1, a file has to have been accessed at least
      two days ago.
    

    This means that your command actually deletes files that were accessed 8 or more days ago.

    Since the time now is

    $ date
    Tue Nov  7 10:29:29 PST 2017
    

    find will require files need to be older than:

    $ date -d 'now - 8 days'
    Mon Oct 30 11:29:05 PDT 2017
    

    In other words, leaving some files from Oct 30 is expected and documented behavior.

    To account for find rounding down, simply use -mtime +6 instead.