Shell Script to Rotate Backup Files Every Few Days

2022-11-27 15:03 (3 years ago)
Shell Script to Rotate Backup Files Every Few Days

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.


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

Categories

Archive