分享比较一个通用的SQL数据库备份脚本
#!/bin/bash
# MySQL数据库信息
DB_HOST="localhost"
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database_name"
# 备份目录和文件名
BACKUP_DIR="/path/to/backup/directory"
BACKUP_FILE="${BACKUP_DIR}/$(date +%Y%m%d%H%M%S).sql"
# 备份保留天数
RETAIN_DAYS=7
# 创建备份目录(如果不存在)
mkdir -p $BACKUP_DIR
# 使用mysqldump命令备份数据库
mysqldump -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME > $BACKUP_FILE
# 检查备份是否成功
if [ $? -eq 0 ]; then
echo "MySQL backup created successfully: $BACKUP_FILE"
else
echo "MySQL backup failed!"
exit 1
fi
# 删除指定天数之前的备份
find $BACKUP_DIR -name "*.sql" -mtime +$RETAIN_DAYS -exec rm {} \;
echo "Old backups deleted successfully."
变量含义:
接下来设置定时任务就行了。
crontab -e
写入任务配置 0 0 * * * /path/to/mysql_backup.sh 即可开启每天定时备份你的数据库了