Files
Kubernetes/File/Shell/file-backup.sh
offends 89a07bc062
All checks were successful
continuous-integration/drone Build is passing
first commit
2025-12-20 21:10:05 +08:00

67 lines
1.8 KiB
Bash
Raw 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
#############################################################################################
# 用途: 文件备份脚本
# 作者: 丁辉
# 更新时间: 2025-12-14
# 配置定时任务
# 每7天凌晨2点执行备份 0 2 * * * /usr/local/bin/file_backup.sh
#############################################################################################
# 要备份的目录
SOURCE_DIR=""
# 备份完成后保存目录
TARGET_DIR=""
# 备份文件命名
TAR_NAME=""
# true=开启清理false=关闭清理
ENABLE_CLEAN="true"
# 清理策略(默认7天外文件删除)
RETENTION_DAYS=7
# 检查源目录是否存在
if [ ! -d "$SOURCE_DIR" ]; then
echo "错误: 源目录 '$SOURCE_DIR' 不存在"
exit 1
fi
# 检查目标目录是否存在,如果不存在则创建
if [ ! -d "$TARGET_DIR" ]; then
echo "目标目录 '$TARGET_DIR' 不存在,正在创建..."
mkdir -p "$TARGET_DIR"
if [ $? -ne 0 ]; then
echo "错误: 无法创建目标目录"
exit 1
fi
fi
# 生成日期格式YYYY-MM-DD
DATE=$(date +"%Y-%m-%d")
# 生成备份文件名
BACKUP_FILENAME="${TAR_NAME}-${DATE}.tar"
BACKUP_PATH="$TARGET_DIR/$BACKUP_FILENAME"
echo "开始备份..."
echo "源目录: $SOURCE_DIR"
echo "目标文件: $BACKUP_PATH"
# 执行备份不压缩只打包为tar
tar -cf "$BACKUP_PATH" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
# 检查备份是否成功
if [ $? -eq 0 ]; then
# 显示备份文件信息
BACKUP_SIZE=$(du -h "$BACKUP_PATH" | cut -f1)
echo "备份完成!"
echo "备份文件: $BACKUP_PATH"
echo "文件大小: $BACKUP_SIZE"
else
echo "错误: 备份失败"
exit 1
fi
if [ "$ENABLE_CLEAN" = "true" ]; then
# 删除7天前的备份文件
find "$TARGET_DIR" -name "${TAR_NAME}-*.tar" -type f -mtime +$RETENTION_DAYS -delete
fi