Last active
August 20, 2020 07:58
-
-
Save jjpeleato/b88fb215c38a7bdd2053b2c9a9e2aa74 to your computer and use it in GitHub Desktop.
Shell script to backup MySQL database.
This file contains hidden or 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 | |
# | |
# Shell script to backup MySQL database. | |
# | |
# Notes: | |
# - MySQL or MariaDB is assumed | |
# - mysqldump is assumed | |
# - gzip is assumed | |
# - UNIX target environment is assumed | |
# | |
# Inspired by: https://gist.github.com/NARKOZ/642511 | |
# | |
# Set these variables | |
NAME="Cron::Dump" | |
DB_HOSTNAME="127.0.0.1" | |
DB_USERNAME="" | |
DB_PASSWORD="" | |
DB_NAME="" | |
# Backup Dest directory. For example: /home/username/.../backups/database | |
DEST="" | |
# Slack hook | |
HOOK="https://hooks.slack.com/services/[key]" | |
# How many days old files must be to be removed | |
DAYS=14 | |
# Linux bin paths | |
MYSQL="$(which mysql)" | |
MYSQLDUMP="$(which mysqldump)" | |
GZIP="$(which gzip)" | |
# Get date in dd-mm-yyyy format | |
NOW="$(date +"%Y-%m-%d_%s")" | |
# Create Backup sub-directories | |
MBD="$DEST/$NOW" | |
install -d $MBD | |
# Archive database dump | |
FILE="$MBD/$DB_NAME.sql" | |
$MYSQLDUMP -h$DB_HOSTNAME -u$DB_USERNAME -p$DB_PASSWORD $DB_NAME --no-tablespaces > $FILE | |
# Compress the file and cleanup | |
cd $DEST && tar -cf $NOW.tar $NOW && $GZIP -9 $NOW.tar && rm -rf $NOW | |
echo "MySQL backup is completed! Backup name is $DEST/$NOW.tar.gz" | |
# Remove old files | |
find $DEST -mtime +$DAYS -exec rm -f {} \; | |
# Send notification | |
curl -X POST -H 'Content-type: application/json' --data "{\"text\":\"\`$DB_NAME\` dump is finished! Database backup successfully on \`$DEST/$NOW.tar.gz\` :white_check_mark:\",\"username\":\"$NAME\"}" "$HOOK" | |
echo | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment