shell作業mysql自動建立檢視以及備份指令碼
阿新 • • 發佈:2019-01-14
前提:已經安裝並且配置好了資料庫軟體
1.要求:新建tom,harry,natasha三個資料庫,然後備份,新建表格並且檢視
指令碼如下
#!/bin/bash MYUSER=root MYPASS=westos MYCMD="mysql -u$MYUSER -p$MYPASS" MYDUMP="mysqldump -u$MYUSER -p$MYPASS" DBPATH=/home/backup for dbname in tom harry natasha do $MYCMD -e "create database $dbname" done [ ! -d "$DBPATH" ] && mkdir -p $DBPATH for dbname in `mysql -uroot -pwestos -e "show databases;" | sed '1,2d' |egrep -v "mysql|schema"` do $MYDUMP $DBNAME | gzip > $DBPATH/${dbname}_$(date +%F).sql.gz done for dbname in tom harry natasha do echo ========${dbname}.test======== $MYCMD -e "use $dbname;select * from ${dbname}.test;" done
執行一下後
檢視資料庫()
檢視備份資料夾
2.要求:資料庫備份,執行script.sh $dbpasswd 備份資料庫中所有庫到/mnt/mysqldump目錄中,備份檔名稱為“庫名稱.sql”,當此檔案存在時進入互動模式,詢問動作,輸入“s”跳過備份,輸入“b”,備份“庫名稱.sql”為“庫名稱_backup.sql”,輸入“O”時,覆蓋原檔案,e表示退出
#!/bin/bash mkdir -p /mnt/mysqldump DATABASE=`mysql -uroot -pwestos -e "show databases;" | sed '1,2d' | egrep -v "mysql|schema"` for MYSQL_NAME in $DATABASE do if [ -e /mnt/mysqldump/${MYSQL_NAME}.sql ];then read -p "${MYSQL_NAME} has been dumped! [S]kip [B]ackup [O]verwrite [E]xit please input the action:" ACTION case $ACTION in s|S) ;; b|B) mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}_backup.sql ;; o|O) mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}.sql ;; e|E) echo -e "Bye" exit 0 esac else mysqldump -uroot -p$1 $MYSQL_NAME > /mnt/mysqldump/${MYSQL_NAME}.sql echo -e "$MYSQL_NAME is backuped!" fi done
試著執行一下
因為剛才第一個指令碼已經備份過了,所以這裡是這樣~