Change date modified of files and delete files other than n days

I am working on a backup script on Linux and for that I need test data: Files that are modified on certain dates and that I can scan for. Of course I could create a file every day for the next month, but that would take a little too long. I found out, that one can use the command “touch” to change the dates for “modified” and “last access”

touch -m -t 202107200100.00 test.txt

This would change the modified date of the file “test.txt” to the 20th of July 20201 01:00:00 at night. This could be integrated in a loop for example. To create 10 files with one modified each day the following script does the job:

#!/bin/bash
i=20
while [ $i -ge 10 ]
do
  touch test_$i.txt
  echo "Hello World" > test_$i.txt
  touch -m -t 202107${i}0100.00 test_$i.txt
  ((i--))
done

Of course, this is pretty simple, but it does the job for my task.

To scan and delete files older than 5 days I can then use …

find . -mtime +5 -delete

… in the same folder.

Pretty neat, huh?