-2

I have a script running on the 1st of each month. On this script I want to delete all files modified before the first of the previous month. For instance. The script will run on the 1st of March. I want to delete all files created before the 1st of February. Is this possible?

2
  • 1
    It is possible and the answer depends on what language are you using for that.
    – maksadbek
    Feb 25, 2018 at 22:27
  • 1
    It is not possible because there is no real concept of creation time. You can have last modified time, though.
    – roaima
    Feb 25, 2018 at 23:08

2 Answers 2

2

Using a shell script:

#!/bin/sh

dir_to_check='/root/temp/somedir'

last_month=$(date -d "-1 month -$(($(date +%d)-1)) days" +%Y-%m-%d)

find "$dir_to_check" ! -newermt "$last_month" -type f -exec rm {} \;

dir_to_check='/root/temp/somedir' Directory to search for files in (hopefully you aren't trying to remove all files on the machine created before last month).

last_month=$(date -d "-1 month -$(($(date +%d)-1)) days" +%Y-%m-%d) - Sets variable to the first day of the previous month.

find "$dir_to_check" ! -newermt "$last_month" -type f -exec rm {} \; - Searches for all files with a modify date older than the first day of last month and removes them.

0

Finding files by creation time is not the simplest, but perhaps files last modified or last accessed would work for you as well?

The simplest but least accurate way is to run a find and select all files modified 31 days ago or more. You can then work on the list of files produced by find or execute the delete within the find command:

  • find files last changed over 31 days ago: find <dir> -type f -mtime +31
  • find and remove files last changed over 31 days ago: find <dir> -type f -mtime +31 -exec rm {} \;

For deciding against access times, just replace -mtime with -atime.

To find files created more than X days ago you could use -newerBt <creation_date> (version 4.3.3 and later). This format could be adapted to use access, modification or change criteria.

  • find files created before 01/01/2018: find <dir> -type f -newerBt 2018-01-01
2
  • Unix/Linux systems don't generally have the concept of a creation date. FYI ctime is not creation time.
    – roaima
    Feb 25, 2018 at 23:06
  • 1
    I just noticed he does ask for modify and then creation.
    – jesse_b
    Feb 25, 2018 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.