Skip to content

Instantly share code, notes, and snippets.

@flangofas
Created March 22, 2020 17:30
Show Gist options
  • Save flangofas/e970160ffb6da687f4b7af02337c378f to your computer and use it in GitHub Desktop.
Save flangofas/e970160ffb6da687f4b7af02337c378f to your computer and use it in GitHub Desktop.
Database backup -- Bash script ready to be used in crontab
#!/bin/bash
################################################################
##
## MySQL Database Backup Script
## Written By: Rahul Kumar
## Updated by: Antonis Flangofas
## URL: https://tecadmin.net/bash-script-mysql-database-backup/
## Last Update: Nov 28, 2019
##
################################################################
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y"`
################################################################
################## Update below values ########################
DB_BACKUP_PATH=''
MYSQL_HOST=''
MYSQL_PORT=''
MYSQL_USER=''
MYSQL_PASSWORD=''
#################################################################
mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "Backup started for all databases"
mysqldump -h ${MYSQL_HOST} \
-P ${MYSQL_PORT} \
-u ${MYSQL_USER} \
-p${MYSQL_PASSWORD} \
--all-databases | gzip > ${DB_BACKUP_PATH}/${TODAY}/all-${TODAY}.sql.gz
if [ $? -eq 0 ]; then
echo "Databases backup successfully completed"
else
echo "Error found during backup"
exit 1
fi
##### Remove backups older than 7 days #####
if [ ! -z ${DB_BACKUP_PATH} ]; then
find ${DB_BACKUP_PATH} -maxdepth 1 -type d -mtime +7 -exec rm -rf "{}" \;
fi
### End of script ####
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment