Last active
March 23, 2021 16:33
-
-
Save chebaby/223b9b7080eba69431ab8d96ab52e555 to your computer and use it in GitHub Desktop.
Bash Script to backup all MySQL databases AND zip www folder WITH email notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
NOW=$(date +"%m_%d_%Y") | |
MYSQL_USER="root" | |
MYSQL_PASSWORD="$(cat /etc/mysqlpass)" | |
DEST="/home/backups" | |
SITES_PATH="/var/www" | |
DATABASES=$(mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database) | |
[ ! -d $DEST ] && mkdir -p $DEST | |
for db in $DATABASES; do | |
if [ "$db" == "performance_schema" ] || [ "$db" == "information_schema" ] || [ "$db" == "mysql" ] || [ "$db" == "sys" ] | |
then | |
continue # Skip rest of this particular loop iteration. | |
fi | |
FILE="${DEST}/${NOW}_${HOSTNAME}_${db}.sql.gz" | |
FILEDATE= | |
# Be sure to make one backup per day | |
[ -f $FILE ] && FILEDATE=$(date -r $FILE +"%F") | |
[ "$FILEDATE" == "$NOW" ] && continue | |
[ -f $FILE ] && mv "$FILE" "${FILE}.old" | |
mysqldump --single-transaction --routines --quick -u $MYSQL_USER -p$MYSQL_PASSWORD -B $db | gzip > "$FILE" | |
chown "$USER":"$USER" "$FILE" | |
rm -f "${FILE}.old" | |
done | |
wait | |
# cd to www directory | |
cd "${SITES_PATH}/"; | |
# for each folder in www directory | |
for SITE in */; do | |
zip -r "/home/backups/${NOW}_${HOSTNAME}_${SITE%/}.zip" "$SITE"; | |
done | |
wait | |
RECIPIENT=notification@email.com | |
MAIL_DATE=$(date +"%d/%m/%Y") | |
MAIL_BODY="Your backup is ready - HOST : $HOSTNAME, PATH : $DEST" | |
echo $MAIL_BODY | mail -s "${HOSTNAME} - backup - ${MAIL_DATE}" $RECIPIENT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment