Very simple MySQL backup bash script

This code backups up mysql databases and gzips them into the current working directory. If you want to backup the mysql table, remove it from the for loop.

#!/bin/bash

usage(){
        echo "Usage $0 <mysql_user> <mysql_password>"
        exit 1
}

if [[ "$2" != "" && "$2" == "" ]]
then
        usage
fi

USER=$1
PASS=$2
if [ "$3" != "" ]
then
  DB_HOST=$3
else
  DB_HOST="localhost"
fi

for db in `mysql -u$USER -p$PASS -h$DB_HOST -e 'show databases' | cut -f2 | awk '{ print $1 }' | grep -v "Database\|mysql\|information_schema\|test"`;
do
  echo "Working with $db"
  mysqldump -u$USER -p$PASS -h$DB_HOST $db > $db.sql
  gzip $db.sql
done;

echo "Finished";
This entry was posted in bash, Commands, Linux, MySQL. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">