Script to backup all mysql database and upload to FTP

In this howto I will show you a simple bash script that dump ALL mysql databases on your server compressed to GZIP and then make a nice tar.gz file with them and upload it to the FTP of your choice.

The script

#!/bin/sh
# System + MySQL backup script
# Copyright (c) 2009 Marchost
# This script is licensed under GNU GPL version 2.0 or above
# ---------------------------------------------------------------------
 
#########################
######TO BE MODIFIED#####
 
### System Setup ###
BACKUP=/root
 
### MySQL Setup ###
MUSER="DBUSER"
MPASS="DBPASSWORD"
MHOST="localhost"
 
### FTP server Setup ###
FTPD="/"
FTPU="FTPUSER"
FTPP="FTPPASSWORD"
FTPS="FTPADDRESS"
 
######DO NOT MAKE MODIFICATION BELOW#####
#########################################
 
### Binaries ###
TAR="$(which tar)"
GZIP="$(which gzip)"
FTP="$(which ftp)"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
 
### Today + hour in 24h format ###
NOW=$(date +"%a%H")
 
### Create hourly dir ###
 
mkdir $BACKUP/$NOW
 
### Get all databases name ###
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
 
### Create dir for each databases, backup databases in different folders ###
  mkdir $BACKUP/$NOW/$db
  FILE=$BACKUP/$NOW/$db/$db.sql.gz
  echo $i; $MYSQLDUMP --add-drop-table --allow-keywords -q -c -u $MUSER -h $MHOST -p$MPASS $db $i | $GZIP -9 > $FILE
done
 
### Compress all databases in one nice file to upload ###
 
ARCHIVE=$BACKUP/server1-$NOW.tar.gz
ARCHIVED=$BACKUP/$NOW
 
$TAR -zcvf $ARCHIVE $ARCHIVED
 
### Dump backup using FTP ###
cd $BACKUP
DUMPFILE=server1-$NOW.tar.gz
$FTP -n $FTPS <<END_SCRIPT
quote USER $FTPU
quote PASS $FTPP
cd $FTPD
mput $DUMPFILE
quit
END_SCRIPT
 
### Delete the backup dir and keep archive ###
 
rm -rf $ARCHIVED

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

great

nice script, clean and str8 :P thanks!

pgn.ro