Created
February 23, 2024 01:27
-
-
Save tjumyk/bc6a8c8835b402af48e043023b427945 to your computer and use it in GitHub Desktop.
Script for backing up a folder, suitable as cron jobs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Adapted from: https://wiki.postgresql.org/wiki/Automated_Backup_on_Linux | |
set -e | |
if [ $# -lt 2 ] ; then | |
echo "$0 <SOURCE_DIR> <BACKUP_DIR>" | |
exit 1 | |
fi | |
SOURCE_DIR="$1" | |
BACKUP_DIR="$2" | |
# Which day to take the weekly backup from (1-7 = Monday-Sunday) | |
DAY_OF_WEEK_TO_KEEP=1 | |
# Number of days to keep daily backups | |
DAYS_TO_KEEP=7 | |
# How many weeks to keep weekly backups | |
WEEKS_TO_KEEP=5 | |
function perform_backups() | |
{ | |
SUFFIX=$1 | |
FINAL_BACKUP_DIR="$BACKUP_DIR/$(date +\%Y-\%m-\%d)$SUFFIX" | |
echo "Making backup directory in $FINAL_BACKUP_DIR" | |
if ! mkdir -p $FINAL_BACKUP_DIR; then | |
echo "Cannot create backup directory in $FINAL_BACKUP_DIR. Go and fix it!" 1>&2 | |
exit 1; | |
fi; | |
echo "Performing backup" | |
rsync -a "$SOURCE_DIR/" "$FINAL_BACKUP_DIR/" | |
} | |
# MONTHLY BACKUPS | |
DAY_OF_MONTH=`date +%d` | |
if [ $DAY_OF_MONTH -eq 1 ]; | |
then | |
# Delete all expired monthly directories | |
find $BACKUP_DIR -maxdepth 1 -name "*-monthly" -exec rm -rf '{}' ';' | |
perform_backups "-monthly" | |
exit 0; | |
fi | |
# WEEKLY BACKUPS | |
DAY_OF_WEEK=`date +%u` #1-7 (Monday-Sunday) | |
EXPIRED_DAYS=`expr $((($WEEKS_TO_KEEP * 7) + 1))` | |
if [ $DAY_OF_WEEK = $DAY_OF_WEEK_TO_KEEP ]; | |
then | |
# Delete all expired weekly directories | |
find $BACKUP_DIR -maxdepth 1 -mtime +$EXPIRED_DAYS -name "*-weekly" -exec rm -rf '{}' ';' | |
perform_backups "-weekly" | |
exit 0; | |
fi | |
# DAILY BACKUPS | |
# Delete daily backups 7 days old or more | |
find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*-daily" -exec rm -rf '{}' ';' | |
perform_backups "-daily" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment