Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- #-------------------------------------------------------------------------------
- # MySQL Database backupscript.
- #
- # Author: CJ
- # Licence: http://opensource.org/licenses/MIT MIT License
- # CopyRight: (c) 2013 - CJ
- #
- #-------------------------------------------------------------------------------
- # Installation
- #-------------------------------------------------------------------------------
- # 1. Place this script in the /usr/local/bin directory
- # 2. change the configuration in this script
- # 3. Add databases to the ignore list
- # 4. Add a cron job for daily backups
- #
- # Example cron:
- # 30 00 * * * /usr/local/bin/mysqlbackup 2>&1 >> /var/log/mysqlbackup.log
- #
- #-------------------------------------------------------------------------------
- # Configuration
- #-------------------------------------------------------------------------------
- # Backup destination
- BACKUPDIR="/db_backups"
- # Howmany backups should be kept
- DAYS_TO_KEEP=7
- # Mysql Information
- MUSER=""; # MySQL username
- MPASS=""; # MySQL password
- MHOST="localhost"; # MySQL hostname/ip
- MPORT="3306"; # MySQL port
- # DO NOT BACKUP these databases
- IGNOREDB="
- information_schema
- test
- "
- #-------------------------------------------------------------------------------
- # Linux bin paths
- # Change this if it can not be autodetected via which command
- #-------------------------------------------------------------------------------
- MYSQL="$(which mysql)"
- MYSQLDUMP="$(which mysqldump)"
- #-------------------------------------------------------------------------------
- # Do not change anything below this line
- #-------------------------------------------------------------------------------
- # Get date in dd-mm-yyyy format
- NOW="$(date +"%d%m%Y")";
- # Get the seven days ago date in dd-mm-yyyy format
- LAST="$(date -d "$DAYS_TO_KEEP days ago" +"%d%m%Y")";
- # Create required directories
- if [ ! -e "$BACKUPDIR" ]; then
- mkdir -p "$BACKUPDIR"
- fi
- # Get all database list first
- DBS="$(mysql -u $MUSER -p$MPASS -h $MHOST -P $MPORT -Bse 'show databases')"
- # Backup the database
- for db in $DBS
- do
- DUMP="yes"
- if [ "$IGNOREDB" != "" ]; then
- for i in $IGNOREDB
- do
- if [ "$db" == "$i" ]; then
- DUMP="no";
- fi
- done
- fi
- if [ "$DUMP" == "yes" ]; then
- # Check for yesterday's backup and delete
- LAST_FILE="$BACKUPDIR/$db""_$LAST.sql.bz2"
- if [ -f "$LAST_FILE" ]; then
- rm "$LAST_FILE";
- fi
- # Create today's backup
- FILE="$BACKUPDIR/$db""_$NOW.sql.bz2"
- $MYSQLDUMP --add-drop-database --opt --lock-all-tables -u $MUSER -p$MPASS -h $MHOST -P $MPORT $db | bzip2 > $FILE
- fi
- done
Advertisement
Add Comment
Please, Sign In to add comment