TringaliLuca

mysqlbak.sh

Aug 8th, 2020 (edited)
69
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2.  
  3. if [ -z "$1" ];  then
  4.     echo "Usage:"
  5.     echo "mysqlbak backup username hostname dbname|ALL mybackup.sql"
  6.     echo "mysqlbak restore  username hostname  dbname|ALL mybackup.sql"
  7.     exit 0
  8. fi
  9.  
  10. action=$1
  11. myuser=$2
  12. myserver=$3
  13. dbname=$4
  14. if [ -z "$5" ]; then
  15.     if [ "$action" == "restore" ]; then
  16.         echo "Input filename missing."
  17.         exit 1
  18.     else
  19.     myfile=backup_$(date +%F).sql
  20.     fi
  21. else
  22.     myfile=$5
  23. fi
  24.  
  25. if [ "$action" == "backup" ]; then
  26.     if [ "$dbname" == "ALL" ]; then
  27.         mysqldump --all-databases --single-transaction --quick --lock-tables=false -u $myuser -h $myserver -p > $myfile
  28.     else
  29.         mysqldump -u $myuser -h $myserver -p $dbname > $dbname-$myfile
  30.     fi
  31. fi
  32.  
  33. if [ "$action" == "restore" ]; then
  34.     if [ "$dbname" == "ALL" ]; then
  35.         mysql -u $myuser -h $myserver -p < $myfile
  36.     else
  37.         read -r -p "Are you sure to DROP DATABASE $dbname? [y/N] " response
  38.         if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
  39.             mysql -u $myuser -h $myserver -p -e "DROP DATABASE $dbname"
  40.         fi
  41.         mysql -u $myuser -h $myserver -p -e "create database $dbname"
  42.         mysql --database=$dbname -u $myuser -h $myserver -p < $myfile
  43.     fi
  44. fi
  45.  
  46. #mysql -u root -h localhost -p
  47. #use dbname
  48. #source bak_database.sql
  49.  
RAW Paste Data