shell腳本-MySQL數(shù)據(jù)庫(kù)備份
準(zhǔn)備:
確保mysql服務(wù)啟動(dòng)
可以通過mysqldump命令來(lái)備份數(shù)據(jù)庫(kù)
1.mysqldump 命令語(yǔ)法:
使用 mysqldump 命令備份一個(gè)數(shù)據(jù)庫(kù)的語(yǔ)法格式如下:
mysqldump -u username -p dbpasswd [tbname ...]> filename.sql
使用 mysqldump 命令備份一個(gè)數(shù)據(jù)庫(kù)中表的語(yǔ)法格式如下:
mysqldump -u username -p dbpasswd [tbname ...]> filename.sql
2.參數(shù):
-s 會(huì)去掉顯示表的邊框
-e 免交互
實(shí)例:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-570531.html
[root@localhost scripts]# mysql -uroot -proot -e "show databases;"
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
+--------------------+
[root@localhost scripts]# mysql -uroot -proot -s -e "show databases;"
Database
information_schema
mysql
performance_schema
test
`再過濾一下就可以得到我們想要備份的一些數(shù)據(jù)庫(kù)列表`
[root@localhost scripts]# mysql -uroot -proot -s -e "show databases;" | grep -Ev "Database|information_schema|mysql|performance_schema|sys"
test
`使用mysqldump備份數(shù)據(jù)庫(kù)`
mysqldump -uroot -proot -B dbname > xxx.sql
`使用mysqldump備份數(shù)據(jù)庫(kù)中的表`
mysqldump -uroot -proot dbname tabname > xxx.sql
1.備份數(shù)據(jù)庫(kù)(可指定數(shù)據(jù)庫(kù))
先確保數(shù)據(jù)庫(kù)服務(wù)啟動(dòng)的情況下,創(chuàng)建shell腳本文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-570531.html
vim 12.sh
#!/bin/bash
DATA=`date +%F-%H-%M-%S`
HOST=localhost
USER=root
PASS=root
BACKUP_DIR=/data/db_backup
DB_LIST=`mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2> /dev/null | grep -Ev "Database|information_schema|mysql|performance_schema|sys"`
for DB in $DB_LIST; do
BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sql
if mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null ; then
echo "$BACKUP_NAME 備份成功!"
else
echo "$BACKUP_NAME 備份失敗!"
fi
done
[root@localhost scripts] bash 12.sh
/data/db_backup/test_.sql 備份成功!
2.備份數(shù)據(jù)庫(kù)中的表(可以指定數(shù)據(jù)庫(kù)、表)
vim 12-1.sh
#!/bin/bash
DATE=`date +%F-%H-%M-%S`
HOST=localhost
USER=root
PASS=root
BACKUP_DIR=/data/db_back_up
DB_LIST=`mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2>/dev/null | grep -Ev "Database|information_schema|mysql|performance_schema|sys"`
for DB in $DB_LIST; do
BACKUP_DB_DIR=$BACKUP_DIR/${DB}_${DATE}
[ ! -d $BACKUP_DB_DIR ] && mkdir -p $BACKUP_DB_DIR &>/dev/null
TABLE_LIST=`mysql -h$HOST -u$USER -p$PASS -s -e "use $DB;show tables;" 2>/dev/null`
for TABLE in $TABLE_LIST; do
BACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sql
if mysqldump -h $HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME ; then
echo "$BACKUP_NAME 備份成功!"
else
echo "$BACKUP_NAME 備份成功!"
fi
done
done
[root@localhost scripts]# bash 12-1.sh
/data/db_back_up/test_2023-07-17-00-28-22/student.sql 備份成功!
到了這里,關(guān)于shell腳本-MySQL數(shù)據(jù)庫(kù)備份的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!