Shell Script to Rotate Backup Files Every Few Days

2022-11-28 00:03 (2 years ago) ytyng

Here is the English translation of the provided Japanese blog article:


If you need to rotate backup files (delete old files) every few days, you can use:

find backup-dir/ -mtime +10 | xargs rm

or use logrotate to achieve this.

Recently, I realized that I can achieve this by sharding the sequential days that increase by one each day using % 10. So, I have been using the following method:

# The shard number changes daily. Rotates every 10 days.
date_shard=$(( ( $(date +%s) / 86400 ) % 10 ))

backup-command > backup-dir/backup.${date_shard}

echo $(date +"%F %T") Done. shard=${date_shard} >> backup-dir/log.txt

It can be implemented simply.


Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011