mysql备份脚本(完全备份,增量备份,差异备份)
时间: 2023-11-15 09:34:43 浏览: 179
MySQL完整备份和增量备份脚本
5星 · 资源好评率100%
以下是MySQL备份脚本的示例,包括完全备份、增量备份和差异备份。
完全备份脚本:
#!/bin/bash
# MySQL full backup script
# Set variables
BACKUP_DIR="/path/to/backup/dir"
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database_name"
DATE=$(date +"%Y-%m-%d")
# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
# Perform backup
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
# Remove backups older than 7 days
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +7 -delete
增量备份脚本:
#!/bin/bash
# MySQL incremental backup script
# Set variables
BACKUP_DIR="/path/to/backup/dir"
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database_name"
DATE=$(date +"%Y-%m-%d")
LAST_BACKUP=$(ls -1t "$BACKUP_DIR"/*.sql.gz 2>/dev/null | head -1)
# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
# Perform backup
if [ -z "$LAST_BACKUP" ]; then
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
else
mysqldump -u "$DB_USER" -p"$DB_PASS" --databases "$DB_NAME" --no-create-info --skip-triggers --single-transaction | gzip > "$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
fi
# Remove backups older than 7 days
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +7 -delete
差异备份脚本:
#!/bin/bash
# MySQL differential backup script
# Set variables
BACKUP_DIR="/path/to/backup/dir"
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database_name"
DATE=$(date +"%Y-%m-%d")
LAST_BACKUP=$(ls -1t "$BACKUP_DIR"/*.sql.gz 2>/dev/null | head -1)
# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
# Perform backup
if [ -z "$LAST_BACKUP" ]; then
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
else
mysqldump -u "$DB_USER" -p"$DB_PASS" --databases "$DB_NAME" --no-create-info --skip-triggers --single-transaction --where="update_time >= '$LAST_BACKUP'" | gzip > "$BACKUP_DIR/$DB_NAME-$DATE.sql.gz"
fi
# Remove backups older than 7 days
find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +7 -delete
注意:这些脚本仅供参考,您需要根据自己的情况进行修改和测试。建议定期测试备份,并将备份文件存储在安全的位置。
阅读全文