MySQL备份01

[root@mysql-master scripts]# cat  mysql_backup.sh 
#!/bin/bash

# MySQL连接信息
mysql_user="root"
mysql_password="Abcd0713@2024"
mysql_defaults_file="/etc/my.cnf"

# 备份目录
backup_dir="/data/backup"

# 获取当前日期和星期几
current_date=$(date +"%Y-%m-%d")
current_day=$(date +"%u")  # %u 格式返回的星期几为 1(周一)到 7(周日)

# 检查备份目录是否存在
if [ ! -d "$backup_dir" ]; then
    mkdir $backup_dir
fi

# 确定是否需要执行全量备份
if [ ! -f "$backup_dir/last_full_backup_info.txt" ]; then
    echo "执行初始全量备份。"
    full_backup_dir="$backup_dir/full_backup_$current_date"
    xtrabackup --defaults-file="$mysql_defaults_file" --user="$mysql_user" --password="$mysql_password" --backup --target-dir="$full_backup_dir"
    if [ $? -eq 0 ]; then
        echo "$(date) - 全量备份成功。" >> "$backup_dir/backup_log.txt"
    else
        echo "$(date) - 全量备份失败。" >> "$backup_dir/backup_log.txt"
    fi
    echo "$current_date" > "$backup_dir/last_full_backup_info.txt"
    exit 0
fi

last_full_backup_date=$(cat "$backup_dir/last_full_backup_info.txt")

if [ $current_day -eq 7 ]; then
    echo "星期天执行全量备份。"
    full_backup_dir="$backup_dir/full_backup_$current_date"
    xtrabackup --defaults-file="$mysql_defaults_file" --user="$mysql_user" --password="$mysql_password" --backup --target-dir="$full_backup_dir"
    if [ $? -eq 0 ]; then
        echo "$(date) - 全量备份成功。" >> "$backup_dir/backup_log.txt"
    else
        echo "$(date) - 全量备份失败。" >> "$backup_dir/backup_log.txt"
    fi
    echo "$current_date" > "$backup_dir/last_full_backup_info.txt"
else
    incremental_backup_dir="$backup_dir/incremental_backup_$current_date"
    echo "根据上次全量备份于 $last_full_backup_date 执行增量备份。"
    xtrabackup --defaults-file="$mysql_defaults_file" --user="$mysql_user" --password="$mysql_password" --backup --target-dir="$incremental_backup_dir" --incremental-basedir="$backup_dir/full_backup_$last_full_backup_date"
    if [ $? -eq 0 ]; then
        echo "$(date) - 增量备份成功。" >> "$backup_dir/backup_log.txt"
    else
        echo "$(date) - 增量备份失败。" >> "$backup_dir/backup_log.txt"
    fi
fi

echo "备份完成。"

# 获取两周前的日期
two_weeks_ago=$(date -d '2 weeks ago' +"%Y-%m-%d")

# 删除两周前的备份文件
find $backup_dir -type d -name "full_backup_*" -ctime +14 -exec rm -r {} \;
find $backup_dir -type d -name "incremental_backup_*" -ctime +14 -exec rm -r {} \;

echo "$(date) - 删除两周前的备份文件。" >> "$backup_dir/backup_log.txt"

  

posted @ 2024-04-12 10:54  beawh  阅读(5)  评论(0编辑  收藏  举报