autoDeploy/backup.sh
2025-02-25 21:52:14 +08:00

86 lines
2.4 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# 获取当前日期和时间
current_time=$(date +"%Y%m%d%H")
userName=$1
password=$2
dbName=$3
host=$4
backUpPath=$5
ossPath=$6
# 备份文件名
backup_file="${dbName}_backUp_${current_time}.sql"
echo "backup_file: "${backup_file}
mkdir ${backUpPath} -p || true
# 备份MySQL数据库
mysqldump --column-statistics=0 -R --opt -u${userName} -p"${password}" -h${host} ${dbName} > ${backUpPath}/"$backup_file"
cd ${backUpPath}
rm sql -rf || true
mkdir sql || true
mv ${backup_file} sql/
tar -czvf ${backup_file}".tar.gz" "sql/"
ossutil cp ${backup_file}".tar.gz" oss://${ossPath}/${backup_file}".tar.gz"
rm -fr sql
calculate_hour_diff() {
# 传入两个时间字符串作为参数
local time1=$1
local time2=$2
# 截取时间字符串中的年、月、日和小时部分
local year1=${time1:0:4}
local month1=${time1:4:2}
local day1=${time1:6:2}
local hour1=${time1:8:2}
local year2=${time2:0:4}
local month2=${time2:4:2}
local day2=${time2:6:2}
local hour2=${time2:8:2}
# 将时间字符串转换为时间戳
local timestamp1=$(date -d "$year1-$month1-$day1 $hour1:00:00" +%s)
local timestamp2=$(date -d "$year2-$month2-$day2 $hour2:00:00" +%s)
# 计算两个时间戳的差值,单位为小时
local diff_hours=$(( ($timestamp2 - $timestamp1) / 3600 ))
# 返回计算结果
echo $diff_hours
}
# 存储60个小时前的备份文件名的数组
old_backup_files=()
cd ${backUpPath}
# 遍168个小时前的备份文件并将文件名存入数组
CURRENT_DATE=$(date +%Y%m%d%H)
for file in ${dbName}--*.sql.tar.gz; do
file_date=$(echo "$file" | grep -oP "\d{10}(?=.sql.tar.gz)")
if [ ${#file_date} -le 1 ]; then
continue
fi
echo $file_date
difft=$(calculate_hour_diff $file_date $CURRENT_DATE )
echo difft $difft
if [[ difft -gt 168 ]]; then
echo $file $CURRENT_DATE $file_date $((CURRENT_DATE - file_date))
old_bacup_files+=("$file")
fi
done
# 遍历数组,删除备份文件
for file in "${old_backup_files[@]}"; do
rm "$file" || true
ossutil rm $file oss://${ossPath}/$file -f || true
done
#删除10天前的备份
#delete_date=$(date -d "10 days ago" +%Y-%m-%d)
#delete_file="${dbName}_backup_${delete_date}.sql.tar.gz"
#rm ${backUpPath}/"$delete_file"
# 输出日志
echo "[$current_date $current_time] 执行${dbName}数据库备份并删除10天前备份成功"