shell脚本-MySQL数据库备份
shell脚本-MySQL数据库备份
准备:
确保mysql服务启动
可以通过mysqldump命令来备份数据库
1.mysqldump 命令语法:
使用 mysqldump 命令备份一个数据库的语法格式如下:
mysqldump -u username -p dbpasswd [tbname ...]> filename.sql
使用 mysqldump 命令备份一个数据库中表的语法格式如下:
mysqldump -u username -p dbpasswd [tbname ...]> filename.sql
2.参数:
-s 会去掉显示表的边框
-e 免交互
实例:
[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
`再过滤一下就可以得到我们想要备份的一些数据库列表`
[root@localhost scripts]# mysql -uroot -proot -s -e "show databases;" | grep -Ev "Database|information_schema|mysql|performance_schema|sys"
test
`使用mysqldump备份数据库`
mysqldump -uroot -proot -B dbname > xxx.sql
`使用mysqldump备份数据库中的表`
mysqldump -uroot -proot dbname tabname > xxx.sql
1.备份数据库(可指定数据库)
先确保数据库服务启动的情况下,创建shell脚本
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.备份数据库中的表(可以指定数据库、表)
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 备份成功!