Created
November 4, 2021 01:34
-
-
Save pacmac/db76240670c069b8e9d6c13843d97775 to your computer and use it in GitHub Desktop.
Restore a MYSQL database using raw .sql or gzipped .sql.gz file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MYSQL="$(which mysql)"; | |
GUNZIP="$(which gunzip)"; | |
## Usage | |
if [ $1 == "help" ];then | |
echo "usage myrestore [DBNAME] [filename.sql|filename.sql.gz]" | |
echo "myrestore MYDB mydb.12345.sql.gz"; | |
exit 0; | |
fi | |
## MAIN | |
if [ ! $2 ];then | |
read -e -i "" -p "Enter Database Name : " DBN; | |
read -e -i "" -p "Enter sql filename : " FN; | |
else | |
DBN="$1"; | |
FN="$2"; | |
fi | |
## Check if sql file exists | |
if [ ! -f "$FN" ];then | |
echo "$FN does not exist in this folder." | |
exit 1; | |
fi | |
## Check if file is gzipped | |
if [[ "$FN" == *.gz ]];then | |
ZIP="1"; | |
fi | |
## Get password | |
read -e -i "" -p "Enter mysql root password : " PWD; | |
## Check if Database Exists. | |
EXISTS=$($MYSQL -u root -p$PWD -e "SHOW DATABASES LIKE '$DBN';") | |
if [ "$EXISTS" ];then | |
echo "Database $DBN Already Exists."; | |
exit 0; | |
else | |
## Restore Database | |
echo "Restoring Database $DBN..."; | |
OK=$($MYSQL -u root -p$PWD -e "CREATE DATABASE $DBN;"); | |
echo "$OK"; | |
# exit 0; | |
if [ "$ZIP" ];then | |
OK=$($GUNZIP < $FN | $MYSQL -u root -p$PWD $DBN); | |
else | |
OK=$($MYSQL -u root -p$PWD $DBN); | |
fi | |
## Check if All is OK (no output) | |
if [ "$OK"];then | |
echo "$OK"; | |
echo "$DBN Restore FAILED."; | |
else | |
echo "$DBN Successfully Restored."; | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment