Skip to content

Instantly share code, notes, and snippets.

@hyunto
Created January 30, 2018 07:28
Show Gist options
  • Save hyunto/c2a91178fc86ac35fa6eefc48db9ddcc to your computer and use it in GitHub Desktop.
Save hyunto/c2a91178fc86ac35fa6eefc48db9ddcc to your computer and use it in GitHub Desktop.
backup data using rsync
#!/bin/bash
set -e
DATE="`date +%Y%m%d_%H%M%S`"
TYPE=""
SRC_DIR=""
DEST_DIR=""
BACKUP_DIR=""
BACKUP_FILE="$HOSTNAME"
LOG_PATH="/var/log/backup_rsync.log"
print_usage() {
cat <<EOF
Description : Backup data using rsync
Usage: $0 [options]
-t Choose backup types. Available value : [ LOCAL ]
-s Source data directory
-d Destination backup directory
-b Directory for saving a archive file
-f (Optional) Backup file name. (Default : $BACKUP_FILE)
-l (Optional) Log directory (Default : $LOG_PATH)
-h Print usage
Example :
$0 -t LOCAL -s /data -d /backup/tmp -b /backup
$0 -t LOCAL -s /data -d /backup/tmp -b /backup -f rsync_backup_file -l /data/logs/backup_rsync.log
EOF
}
function print_start_msg() {
echo -e "[`date \"+%Y-%m-%d %H:%M:%S\"`] Start Rsync Backup. Type : $1" >> $LOG_PATH
}
function print_finish_msg() {
echo -e "[`date \"+%Y-%m-%d %H:%M:%S\"`] Done.\n" >> $LOG_PATH
}
function print_msg() {
echo -e "[`date \"+%Y-%m-%d %H:%M:%S\"`] $1" >> $LOG_PATH
}
if [ "$#" -eq "0" ]; then
print_usage
exit 13
fi
while getopts ":t:s:d:l:b:f:h" opt
do
case $opt in
t)
TYPE="$OPTARG"
;;
s)
SRC_DIR="$OPTARG"
;;
d)
DEST_DIR="$OPTARG"
;;
l)
LOG_PATH="$OPTARG"
;;
b)
BACKUP_DIR="$OPTARG"
;;
f)
BACKUP_FILE="$OPTARG"
;;
\?)
echo "[ERROR] Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "[ERROR] Option -$OPTARG requires an argument." >&2
exit 1
;;
h | *)
print_usage
exit 0
;;
esac
done
if [[ -z "$TYPE" || -z "$SRC_DIR" || -z "$DEST_DIR" || -z "$BACKUP_DIR" ]];
then
echo -e "[ERROR] Missing a required parameter."
exit 1
fi
case $TYPE in
"LOCAL")
print_start_msg $TYPE
print_msg "Backup $SRC_DIR directory to $DEST_DIR."
(time rsync -azvc --delete $SRC_DIR $DEST_DIR) >> $LOG_PATH 2>&1
print_msg "Archive and Compress $DEST_DIR to $BACKUP_DIR/$BACKUP_FILE-$DATE.tar.gz"
(time tar -czf $BACKUP_DIR/$BACKUP_FILE-$DATE.tar.gz $DEST_DIR) >> $LOG_PATH 2>&1
print_finish_msg
exit 0
;;
*)
echo "[ERROR] Unknown type value. : $TYPE"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment