Backup and Restore MySQL database on Linux Platform

A while back probably couple years ago I wrote bash scripts to backup and restore MySQL db on Linux platform mainly for debugging and/or troubleshooting purposes and here they are:

########################################
### backup.sh Backup mysql db script ###
########################################
#!/bin/bash
 
userhome=$(eval echo "~$USER")
echo "Executing under $USER context"
 
echo "Enter db username: "
read -s  USER
echo "Enter db password: "
read -s PASS
read -p "Enter database name: " DBNAME
 
### Backing up database ###
mysqldump -u$USER -p"$PASS" $DBNAME > $userhome/$DBNAME.sql
 
 
echo "---------------------------------------------------------------------------------"
echo "if no error, $DBNAME backup will be saved to $userhome/$DBNAME.sql"
echo "---------------------------------------------------------------------------------"
##########################################
### restore.sh restore mysql db script ###
##########################################
#!/bin/bash
 
userhome=$(eval echo "~$USER")
echo "Executing under $USER context"
 
echo "Enter dba username: "
read -s  USER
echo "Enter dba password: "
read -s PASS
read -p "Enter database name: " DBNAME
read -p "Enter database backup location (.sql): " DBBACKUPSQL
 
### restore backup database ###
mysql -u$USER -p"$PASS" -e "drop database $DBNAME;"
mysql -u$USER -p"$PASS" -e "create database $DBNAME;"
mysql -u$USER -p"$PASS" $DBNAME < $DBBACKUPSQL
 
echo "---------------------------------------------------------------------------------"
echo "if no error, $DBBACKUPSQL backup has been restored"
echo "---------------------------------------------------------------------------------"
To backup, at terminal execute backup.sh
# bash backup.sh 

it will prompt you for the database username and password and db.sql will be saved to the home directory of the user you use to execute this script.

To restore, at the terminal execute restore.sh

it will prompt you for the database admin username, password, and the backup script .sql location.

Leave a Reply

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