Shell 指令碼備份MySQL資料庫

來源:互聯網
上載者:User

標籤:shell   mysql   mysqldump   

(1)思路


  <1>安裝MySQL資料庫


  <2>建立資料庫,表,插入資料

 

  <3>授權一個用於備份資料庫的使用者名稱和密碼


  <4>備份資料庫的命令: mysqldump -u root -p 1234 -d MySQLDB > 1.sql


  <5>引入if語句實現備份全部資料庫


  <6>引入for迴圈語句,實現備份多個資料庫


(2)實戰案例

 編寫MySQLDatabase Backup指令碼,可以實現備份任意資料庫,輸入A,就備份A庫,輸入B,就備份B庫,輸入C,就備份C庫,輸入ALL,就備份全部資料庫


(3)安裝步驟

 <1>安裝MySQL資料庫

  yum  install  mysql-server  mysql-devel  mysql-libs  -y

   

    <2>重啟MySQL資料庫

       service mysqld   restart


   <3>進入資料庫命令列模式

      建立3個資料庫,分別在3個資料庫中建立3張表,在表中插入一條資料

      create  database  jfedu;

      use  jfedu;

      create table t1(id varchar(20),name varchar(20));

      insert into t1 values("1","daqi");

      desc t1;

      select * from  t1;

  注釋:

             不要忘記驗證資料庫,表 ,資料是否都已經建立成功


  <4>授權一個用於備份資料庫的使用者名稱和密碼

   grant all on *.* to [email protected] identified by "123456";


 <5> 

  

#!/bin/bash

#2017年12月6日10:28:54

#by author daqi

#mysqldump MySQLDB

BAKDIR=/data/backup/mysql/`date +%Y-%m-%d`

MYSQLDB=$*

MYSQLPW=123456

MYSQLUSR=backup

#must use root user run scripts 必須使用root使用者運行,$UID為系統變數

if  [ $UID -ne 0 ];then

   echo This script must use the root user ! ! ! 

   sleep 2

   exit

fi

#判斷使用者輸入參數的個數

if [ -z "$1" ];then

 echo -e "\033[36mPlease Select mysqldump MySQLDB:jfedu|taobao|jd|all\033[0m"

 exit 0

fi


#Define DIR and mkdir DIR 判斷目錄是否存在,不存在則建立


if

   [ ! -d  $BAKDIR ];then

   mkdir  -p  $BAKDIR

fi


#Use mysqldump backup Databases

if [ $1 == "all" ];then

    /usr/bin/mysqldump -u$MYSQLUSR -p$MYSQLPW --all-databases >$BAKDIR/ALL_DB.sql

    echo  "The $BAKDIR/ALL_DB.sql Mysql  Database backup successfully "

else

  for i in `echo $MYSQLDB`

  do

   /usr/bin/mysqldump -u$MYSQLUSR -p$MYSQLPW -d $i >$BAKDIR/${i}_db.sql

   echo  "The mysql databases $BAKDIR/${i}_db.sql successfully "

 done

fi



Shell 指令碼備份MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.