Skip to content

Instantly share code, notes, and snippets.

@daniel70
Last active January 24, 2017 13:30
Show Gist options
  • Save daniel70/6269559 to your computer and use it in GitHub Desktop.
Save daniel70/6269559 to your computer and use it in GitHub Desktop.
Purge backups with this simple script.
#!/usr/bin/env python
# author: Daniel van der Meulen
# email:
# purpose: Delete older backup files from directory
# We keep files younger than 1 month AND
# from the first day of the month from this year AND
# from the first day of the year
# Files that should not be deleted can be put in the exempt list
# curl -L https://gist.github.com/daniel70/6269559/download | tar xz --strip-components=1
import sys, os, time
from datetime import date
exempt = ['create_backup.sh']
now = time.time()
month_ago = now - 30 * 24 * 60 * 60
year_ago = now - 365 * 24 * 60 * 60
def keep(ts):
# keep if younger than one month
if ts > month_ago:
return True
d = date.fromtimestamp(ts)
# keep if jan 1st
if d.day == 1 and d.month == 1:
return True
# keep if 1st of month and less than 1 year old
if d.day == 1 and ts > year_ago:
return True
return False
def purge(folder):
this_file = sys.argv[0]
for f in [os.path.join(folder, f) for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]:
# don't delete myself
if os.path.basename(this_file) == os.path.basename(f):
print("sanctuary: %s" % f)
continue
if os.path.basename(f) in exempt:
print("exempt: %s" % f)
continue
if not keep(os.path.getmtime(f)):
os.remove(f)
print("removing: %s" % f)
else:
print("keeping: %s" % f)
if __name__ == '__main__':
# make sure a valid path was given
if len(sys.argv) < 2:
sys.exit('Usage: %s <dirname>' % os.path.basename(sys.argv[0]))
if not os.path.isdir(sys.argv[1]):
sys.exit('Error: directory %s does not exist!' % sys.argv[1])
purge(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment