Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: Delete all files older than 1 month, but leave files from Mondays

Tags:

bash

sh

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.

like image 818
freento Avatar asked Nov 17 '13 18:11

freento


1 Answers

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:

  • Using date -r to get the last modification date of a file directly
  • Using %a to work with more comprehensible weekday names
  • Just echo the rm "$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"' -- {} \;
like image 192
janos Avatar answered Oct 08 '22 19:10

janos