Skip to content

Instantly share code, notes, and snippets.

@non7top
Created May 9, 2015 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save non7top/d403b4565cba8ea1b460 to your computer and use it in GitHub Desktop.
Save non7top/d403b4565cba8ea1b460 to your computer and use it in GitHub Desktop.
#!/bin/bash
# by non7top
LC_ALL=C
LANG=C
EMAIL=""
RETENTION=10
SOURCE=/backups/fusion
DEST=/mnt/backups
USB_LABEL="backups"
EXCLUDE="--exclude=DEV"
LOG_FILE=/var/tmp/usb-backup-$(date +"%F_%H-%M-%S").log
__exit() {
mail -s "$STATUS - [usb-backup] - `date`" $EMAIL < $LOG_FILE
:
}
__log() { echo ">> `date` :: $*" ; }
exec > $LOG_FILE 2>&1
WEEK="$(( $(date +%W )%2 ))"
# run on odd weeks only, i.e. every second week
if [ $WEEK -eq 0 ]; then
__log "Skipping script run on even week: $WEEK"
__log "Exit"
exit 0
fi
trap __exit EXIT
__log "Backup to usb started"
k=$( df -hP $DEST | tail -n1|awk '{print $6}' )
if [ "x$k" != "x$DEST" ]; then
mount LABEL=$USB_LABEL /mnt/backups || { __log "Unable to mount usb drive"; STATUS="Failed"; exit 1; }
fi
D="$DEST/fusion_$(date +%F)"
STATUS="Success"
__check_space () {
NEED=$( du -smc $EXCLUDE $SOURCE/* |grep total|awk '{print $1}' )
AVAIL=$( df -mP /mnt/backups/|tail -n1 |awk '{print $4}' )
if [ $AVAIL -lt $NEED ]; then
__log "No enough space in destination - need: ${NEED}MB have: ${AVAIL}MB"
return 1
fi
}
__check_space
if [ $? -eq 1 ]; then
# Delete 1 latest backup
B=$( ls -1d /mnt/backups/fusion_*|sort -n|head -n1 )
__log "No enough space so delete one latest backup: $B"
fi
__check_space
if [ $? -eq 1 ]; then
# Error out
__log "No enough space after cleanup, manual intervention required"
STATUS="Failed";
exit 1
fi
__log "Starting rsync"
rsync --stats -aHS $EXCLUDE $SOURCE/ $D/
res=$?
__log "Finished rsync with return code: $res"
__delete_old() {
O=$( ls -1d $DEST/fusion_*|sort -nr|awk "NR >$RETENTION" )
__log "Deleting old backups with retention $RETENTION: "
echo "$O"
__log "Remaining backups:"
ls -ld $DEST/fusion_*
}
if [ $res -eq 0 ]; then
__delete_old
else
STATUS="Warning"
__log "Not purging old backups since rsync completed with error"
fi
__log "Unmounting usb drive"
umount /mnt/backups
__log "Backup complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment