Skip to content

Instantly share code, notes, and snippets.

@ngugijames
Created December 30, 2018 12:57
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 ngugijames/583faf3bfd2cfa793e5348efd83fb9c5 to your computer and use it in GitHub Desktop.
Save ngugijames/583faf3bfd2cfa793e5348efd83fb9c5 to your computer and use it in GitHub Desktop.
MySQL backup script
#!/bin/sh
BACKUP=/var/www/html/mysql_backup/backups
cd $BACKUP
sudo mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")
MUSER="user"
MPASS="pass"
MHOST="host"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
MAIL="info@example.com"
STATUSFILE="/tmp/statusfile.$NOW"
# It succeeds but stderr will get:
# Warning: Using a password on the command line interface can be insecure.
# You can fix this with the below hack:
credentialsFile=/mysql-credentials.cnf
echo "[client]" > $credentialsFile
echo "user=$MUSER" >> $credentialsFile
echo "password=$MPASS" >> $credentialsFile
echo "host=$MHOST" >> $credentialsFile
echo "Backup report from $NOW" > $STATUSFILE
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
$MYSQLDUMP --defaults-extra-file=$credentialsFile --lock-all-tables $db | $GZIP -9 > $FILE
if [ "$?" -eq "0" ]; then
echo "$db backup is OK" >> $STATUSFILE
else
echo "##### WARNING: ##### $db backup failed" >> $STATUSFILE
fi
done
# delete backups older than 1 week
find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf {} \;
mail -s "Backup report for $NOW" -- $MAIL < $STATUSFILE
rm $STATUSFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment