一. mysql 数据库备份 sh 脚本
1. vim sqlback.sh
bash
#!/bin/bash
USER="root" #账号
PASSWORD="123456" #密码
DATABASE="test" #数据库名
BACKUP_DIR="/home/dev/mysql" #备份存的目录
TIMESTAMP=$(date +"%F") #带时间命名
BACKUP_FILE="$BACKUP_DIR/$DATABASE-$TIMESTAMP.sql"
mysqldump -u $USER -p$PASSWORD $DATABASE > $BACKUP_FILE
if [ $? -eq 0 ]; then
echo "Backup succeeded: $BACKUP_FILE"
else
echo "Backup failed"
fi
2. chmod +x sqlback.sh
3. ./sqlback.sh
4. 执行完后会在 /home/dev/mysql 目录下生成备份文件
二. mysql 数据库恢复流程
1. 如果数据库没有存在,要先创建数据库
bash
mysql -u root -p -e "CREATE DATABASE test;"
2. vim sqlRestore.sh
bash
#!/bin/bash
# MySQL credentials
USER="root" #账号
PASSWORD="123456" #密码
DATABASE="test" #数据库名
BACKUP_FILE="/home/dev/mysql/test-2024-06-04.sql.sql" #数据库备份的目录
# Run mysql to restore
mysql -u $USER -p$PASSWORD $DATABASE < $BACKUP_FILE
# Check if the command succeeded
if [ $? -eq 0 ]; then
echo "Restore succeeded: $DATABASE"
else
echo "Restore failed"
fi