I have a lot of daily backup archives. To manage disk usage, I need a bash script that will delete all files older than 1 month, but keep all files created on Mondays, even if they are older than 1 month.
For example, this will delete all files last modified more than 30 days ago:
find /path/to/files* -type f -mtime +30 -delete
But I don't really know how to keep files created on Mondays.
Slightly simpler and more cautious version of @JoSo's answer:
find /path/to/files -type f -mtime +30 \
-exec sh -c 'test $(date +%a -r "$1") = Mon || echo rm "$1"' -- {} \;
The differences:
date -r
to get the last modification date of a file directly%a
to work with more comprehensible weekday namesrm "$1"
first to review what will be deleted. If looks good, then either stick | sh
at the end to really execute, or remove the echo
However, @JoSo is right to point out that date +%a
is locale dependent, so these versions would be indeed safer:
find /path/to/files -type f -mtime +30 \
-exec sh -c 'test $(date +%u -r "$1") = 1 || echo rm "$1"' -- {} \;
find /path/to/files -type f -mtime +30 \
-exec sh -c 'test $(LC_TIME=C date +%a -r "$1") = Mon || echo rm "$1"' -- {} \;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With