server-scripts/rsync-backup/rsync-backup.sh

79 lines
2.2 KiB
Bash
Executable File

#!/bin/bash
#################################################################
# Check availability of software
#################################################################
function availability {
if [[ ! $(command -v $1) ]]; then
echo Error: '$1' is not available but required. Please install it!
exit 1
fi
}
availability mail
availability rsync
#################################################################
# Get arguments
#################################################################
missingArg()
{
echo "Error: Please define the configuration to be used!"
echo " Usage: $0 -c <configuration_file>"
exit 1
}
while getopts "c:" opt
do
case "$opt" in
c ) CONFIG_FILE="$OPTARG" ;;
? ) missingArg ;;
esac
done
# Check if config was empty
if [ -z "$CONFIG_FILE" ]
then
missingArg
fi
# Check if config file exists
if [ ! -f $CONFIG_FILE ]
then
echo "$CONFIG_FILE does not exist!"
exit 1
fi
source $CONFIG_FILE
#################################################################
# Loop through array and invoke rsync
#################################################################
date_styled=$(date -d "today" +"%Y%m%d_%H%M")
for i in "${SRC_DIRS[@]}"
do
echo "" >> /tmp/rsync_log_$date_styled
echo "======================================================" >> /tmp/rsync_log_$date_styled
echo "${i^^}" >> /tmp/rsync_log_$date_styled
echo "======================================================" >> /tmp/rsync_log_$date_styled
rsync -av --modify-window=1 --delete --compress --rsh="ssh -p $SSH_PORT -i $SSH_KEY" $i $SSH_USER@$SSH_HOST:$DST_DIR | grep -E '^deleting|[^/]$' >> /tmp/rsync_log_$date_styled
done
#################################################################
# Send email with information and hashes
#################################################################
sed -i '1s/^/Hey there!\n\nI created a new backup. See the log below.\n/' /tmp/rsync_log_$date_styled
mail -s "Backup created ($date_styled)" $EMAIL < /tmp/rsync_log_$date_styled
#################################################################
# Delete log
#################################################################
rm -f /tmp/rsync_log_$date_styled
exit 0