Henry
发布于 2024-04-16 / 25 阅读
0
0

Linux 备份文件脚本

背景简介

日常应用中,需要自动备份某些文件,因此准备此脚本。

环境配置

  1. 系统:Debian 6.1.66-1 (2023-12-09) x86_64 GNU/Linux

详细步骤

创建脚本文件并添加可执行权限

root@k8s-master:/vm-server-bk/docker-repo/shell# touch backup-firefly-iii.sh
root@k8s-master:/vm-server-bk/docker-repo/shell# chmod +x backup-firefly-iii.sh 

编辑脚本

root@k8s-master:/vm-server-bk/docker-repo/shell# nano backup-firefly-iii.sh
root@k8s-master:/vm-server-bk/firefly-iii/shell# cat backup-firefly-iii.sh 
#!/bin/bash

# 备份目录
BACKUP_DIR="/vm-server-bk/firefly-iii/bk-file"
LOG_DIR="/vm-server-bk/firefly-iii/logs"

# 源目录
SOURCE_DIR="/vm-server/prod/firefly_iii"

# 获取当前日期
CURRENT_DATE=$(date +%Y%m%d)

# 备份文件名
BACKUP_FILE_NAME="$BACKUP_DIR/firefly_iii_$CURRENT_DATE.tar.gz"

# 判断备份目录是否存在,如果不存在则创建
if [ ! -d "$BACKUP_DIR" ]; then
  mkdir -p "$BACKUP_DIR"
  echo "Backup directory created: $BACKUP_DIR"
fi

echo "源路径:$SOURCE_DIR"
echo "备份文件:$BACKUP_FILE_NAME"

# 开始备份文件
tar --acls --xattrs -cvzf "$BACKUP_FILE_NAME" "$SOURCE_DIR"

# 删除历史备份 - 一周以前
find "$BACKUP_DIR" -name "firefly_iii_*.tar.gz" -type f -mtime +7 -exec rm {} \;
echo "Backup completed and old backups deleted."

脚本部分详解:

  • if [ ! -d "$BACKUP_DIR" ]: 判断备份路径是否存在
  • tar
    • --acls: 保留文件和目录的访问控制列表。
    • --xattrs:保留文件和目录的扩展属性。
    • -czvf: 创建一个 gzip 压缩的 tar 归档。
  • find
    • -type f: 只寻找普通文件(f 代表普通文件),而不包括目录、符号链接等。
    • -mtime +7: 只寻找那些修改时间超过 7 天的文件。mtime 代表文件内容最后修改时间,+7 表示 7 天以前。
    • -exec rm {} \; :对找到的每个文件执行 rm 命令。rm 是删除文件的命令,{} 会被 find 指令找到的文件名替换。\; 表示命令结束。注意,-exec 和 \; 之间必须有一个空格。

配置定时任务

root@k8s-master:/vm-server-bk/firefly-iii/shell# crontab -e

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
1 1 * * * /vm-server-bk/firefly-iii/shell/backup-firefly-iii.sh >> /vm-server-bk/firefly-iii/logs/backup_firefly_iii_$(date +\%Y\%m\%d_\%H\%M\%S).log

解析:

  • 1 1 * * *:这是 cron 任务的调度规则,由五个域组成,每个域代表一个时间单位。
    • 1:分钟域,表示在每小时的第 1 分钟执行。
    • 1:小时域,表示在每天的凌晨 1 点执行。
    • *:日期域,表示在每个月的每一天执行。
    • *:月份域,表示在每年的每个月执行。
    • *:星期域,表示在每周的每一天执行。

至此,定时备份文件的配置已完成!


评论