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.
As
find
to my knowledge has no weekday check, you need to call an external program.Update: Using the
-r
switch todate
(Kudos to Janos) and only testing, not deleting inside the shell command probably yields the cleanest possible version:you can use
to get the date the file was created.
Then extract the date with cut to have a var like myvar=yyyymmdd
and finally use
it will return the day of week, if it returns 1 it was monday. In my case it return 4 because 22/08/2013 was a Thursday
Edit : if you can get all these working as a simple command line as Jo So suggest, it's better !
What about avoiding subprocesses in loop:
Slightly simpler and more cautious version of @JoSo's answer:
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 theecho
However, @JoSo is right to point out that
date +%a
is locale dependent, so these versions would be indeed safer: