Skip to content

Instantly share code, notes, and snippets.

@mxsrc
Created September 5, 2013 12:55
Show Gist options
  • Save mxsrc/6449723 to your computer and use it in GitHub Desktop.
Save mxsrc/6449723 to your computer and use it in GitHub Desktop.
Backup script using rsync and ssh
#!/bin/sh
if [ $# != 2 ]
then
echo usage: $0 SOURCE HOST
exit 1
fi
SOURCE=$1
BACKUP_DIR=backup
HOST=$2 # place this in ~/.ssh/config
EXCLUDE=$HOME/.rsync/exclude
DATE_FORMAT='%Y-%m-%d-%H:%M' # see man date for additional info
###############################################################################
DATE=$(date "+$DATE_FORMAT")
LOG_TMP='/tmp/backup_log_'$DATE
OPTIONS='-azP -e ssh --delete --delete-excluded --exclude-from='$EXCLUDE' --link-dest=../current --log-file='$LOG_TMP
CMD='rsync '$OPTIONS' '$SOURCE'/ '$HOST':'$BACKUP_DIR'/incomplete_back_'$DATE
# create backup directory if necessary
ssh $HOST 'if [[ ! -e '$BACKUP_DIR' ]]; then mkdir '$BACKUP_DIR'; fi; if [[ ! -e '$BACKUP_DIR'/logs ]]; then mkdir '$BACKUP_DIR'/logs; fi;'
# actually do the backup
if $CMD # if backup is succesful move
then
SSH_CMD="'mv $BACKUP_DIR/incomplete_back_"$DATE" "$BACKUP_DIR"/back-"$DATE" && rm -f "$BACKUP_DIR"/current && ln -s back-"$DATE" "$BACKUP_DIR"/current'"
ssh $HOST "'"$SSH_CMD"'"
fi
# send logfile
if [ -e $LOG_TMP ]
then
scp $LOG_TMP $HOST:$BACKUP_DIR/logs/log_$DATE &> /dev/null
rm $LOG_TMP
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment