ruk·si

🔨 Bash
Backup Script

Updated at 2016-12-10 02:42
#!/bin/bash

# https://nicaw.wordpress.com/2013/04/18/bash-backup-rotation-script/

# crontab suggestion:
# crontab -e
# 0 4 * * * /home/webserver/backup.sh
# crontab -l

MASTER_ROOT=/home/webserver

STORAGE=$MASTER_ROOT/backups

MONTHLY_ROOT=$STORAGE/monthly
WEEKLY_ROOT=$STORAGE/weekly
DAILY_ROOT=$STORAGE/daily

# Make sure all directories exist
mkdir -p $MONTHLY_ROOT
mkdir -p $WEEKLY_ROOT
mkdir -p $DAILY_ROOT

MONTH_DAY=`date +"%d"`
WEEK_DAY=`date +"%u"`

# On first month day do
if [ "$MONTH_DAY" -eq 1 ] ; then
  destination=$MONTHLY_ROOT
else
  # On saturdays do
  if [ "$WEEK_DAY" -eq 6 ] ; then
    destination=$WEEKLY_ROOT
  else
    # On other days do
    destination=$DAILY_ROOT
  fi
fi

target_path=$destination/blog-`date +"%Y-%m-%d"`.zip
if [ -f $target_path ]; then
    rm $target_path
fi

zip -r $target_path $MASTER_ROOT/blog

# monthly - keep for 300 days
find $MONTHLY_ROOT/ -maxdepth 1 -mtime +300 -type f -exec rm -v {} \;

# weekly - keep for 60 days
find $WEEKLY_ROOT/ -maxdepth 1 -mtime +60 -type f -exec rm -v {} \;

# daily - keep for 14 days
find $DAILY_ROOT/ -maxdepth 1 -mtime +14 -type f -exec rm -v {} \;