Stan Stan - 5 months ago 13
Bash Question

Shell script to backup all databases and www directory

I have a simple shell script which backup once a week whole

www
directory and single database. It is working perfectly.. Now I want to extend it a little bit and make it to backup all databases not just one. How can I do this?

This is the current script

#!/bin/bash
NOW=$(date +"%Y-%m-%d-%H%M")
FILE="backup.$NOW.tar"
BACKUP_DIR="/home/user/backups/"
WWW_DIR="/var/www/"

DB_USER="dbuser"
DB_PASS="dbpass"
DB_NAME="dbName"
DB_FILE="backup.$NOW.sql"

WWW_TRANSFORM='s,^home/user/www,'
DB_TRANSFORM='s,^home/user/backups,database,'


tar -cf $BACKUP_DIR/$FILE --transform $WWW_TRANSFORM $WWW_DIR
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME > $BACKUP_DIR/$DB_FILE

tar --append --file=$BACKUP_DIR/$FILE --transform $DB_TRANSFORM $BACKUP_DIR/$DB_FILE
rm $BACKUP_DIR/$DB_FILE
gzip -9 $BACKUP_DIR/$FILE

echo 'backup finished', $FILE

Answer

You can simple use show databases command. Read all the databases in for loop like this and call mysqldump command

databases=`mysql --user=$DB_USER --password=$DB_PASS -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

for db in $databases; do
        echo "Dumping database: $db"
        mysqldump --force --opt --user=$DB_USER--password=$DB_PASS --databases $db > $BACKUP_DIR/`date +%Y%m%d`.$db.sql
done
Comments