Skip to content

Instantly share code, notes, and snippets.

@bsemot
Last active November 3, 2023 03:01
Show Gist options
  • Save bsemot/484417af91ef72eada6d24deeee54da9 to your computer and use it in GitHub Desktop.
Save bsemot/484417af91ef72eada6d24deeee54da9 to your computer and use it in GitHub Desktop.
#!/bin/bash
### BINARIES ###
TAR="$(which tar)"
GZIP="$(which gzip)"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
### SYSTEM SETUP ###
BACKUP_PARENT_DIR="_PATH_TO_BACKUP_DIRECTORY_"
BACKUP_FOR_N_DAYS=7
### MYSQL SETUP ###
# array of database names to be backed up, separated with 1 whitespace
# be sure that the database username and password has been granted to all databases in the array
declare -a DATABASES=("database_name_1" "database_name_2" "database_name_3")
DB_HOSTNAME="localhost"
DB_USERNAME="_YOUR_DATABASE_USERNAME_"
DB_PASSWORD="_YOUR_DATABASE_PASSWORD_"
### CONNECTION CHECKS ###
# Read MySQL password from stdin if empty
if [ -z "${DB_PASSWORD}" ]; then
echo -n "Enter MySQL ${DB_USERNAME} password: "
read -s DB_PASSWORD
echo
fi
# Check MySQL password
echo exit | ${MYSQL} --user=${DB_USERNAME} --password=${DB_PASSWORD} -B 2>/dev/null
if [ "$?" -gt 0 ]; then
echo "MySQL ${DB_USERNAME} password incorrect"
exit 1
else
echo "MySQL ${DB_USERNAME} password correct."
fi
### TAKE THE BACKUPS ###
# Create backup directory and set permissions
BACKUP_DATE=`date +%Y_%m_%d`
BACKUP_DIR="${BACKUP_PARENT_DIR}/${BACKUP_DATE}"
echo "Backup directory: ${BACKUP_DIR}"
mkdir -p "${BACKUP_DIR}"
chmod 700 "${BACKUP_DIR}"
# loop through databases and do daily backups
for database in "${DATABASES[@]}"
do
if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
additional_mysqldump_params="--skip-lock-tables"
else
additional_mysqldump_params=""
fi
echo "Creating backup of \"${database}\" database"
${MYSQLDUMP} ${additional_mysqldump_params} --user=${DB_USERNAME} --password=${DB_PASSWORD} ${database} | ${GZIP} > "${BACKUP_DIR}/${database}.gz"
chmod 600 "${BACKUP_DIR}/${database}.gz"
done
### CLEAN-UP ###
# Clean old backups to save disk-space
echo "Cleaning up backups older than ${BACKUP_FOR_N_DAYS} days"
find ${BACKUP_PARENT_DIR}/* -type d -ctime +${BACKUP_FOR_N_DAYS} -exec rm -rf {} \;
@bsemot
Copy link
Author

bsemot commented Nov 21, 2016

Add a crontab like following for daily backups

# Backup databases, daily at 01:00 am every day
# @author: Semih Turgut
0 1 * * * bash /path/to/script/db_backup.sh > /dev/null 2>&1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment