针对GNU/Linux synology_apollolake_418play下的删除数据脚本

1、目的

        一个在 Linux 下的 Bash 脚本,用于每三年删除 /volume1 目录下的文件以及子文件夹下的文件。这个脚本假设你已经有了判断时间间隔是否为三年的方法(比如上述提到的通过记录上一次执行时间并进行比较的方法)。

2、操作

1)假设存在一个脚本文件名为 delete_every_three_years.sh

#!/bin/bash

# 目标目录,即要删除文件的目录
target_directory="/volume1"

# 获取当前日期,格式为YYYY-MM-DD
current_date=$(date +%Y-%m-%d)

# 尝试读取记录上一次执行日期的文件内容
last_execution_date=$(cat /path/to/last_execution_date.txt)

# 分别提取当前日期的年、月、日
current_year=$(date +%Y)
current_month=$(date +%m)
current_day=$(date +%d)

# 如果记录文件存在,提取记录日期的年、月、日
if [ -n "$last_execution_date" ]; then
    last_execution_year=$(echo $last_execution_date | cut -d '-' -f1)
    last_execution_month=$(echo $last_execution_date | cut -d '-' -f2)
    last_execution_day=$(echo $last_execution_date | cut -d '-' -f3)
else
    # 如果记录文件不存在,初始化记录日期为当前日期减三年
    last_execution_year=$(date -d "3 years ago" +%Y)
    last_execution_month=$(date -d "3 years ago" +%m)
    last_execution_day=$(date -d "3 years ago" +%d)
    echo "$last_execution_year-$last_execution_month-$last_execution_day" > /path/to/last_execution_date.txt
fi

# 计算当前日期与记录日期的年、月、日差值
year_diff=$(expr $current_year - $last_execution_year)
month_diff=$(expr $current_month - $last_execution_month)
day_diff=$(expr $current_day - $last_execution_day)

# 判断是否满足三年的时间间隔条件
if [ $year_diff -gt 2 ] || [ $year_diff -eq 2 -a $month_diff -gt 0 ] || [ $year_diff -eq 2 -a $month_diff -eq 0 -a $day_diff -ge 0 ] || [ $year_diff -eq 3 ]; then
    # 如果满足条件,输出提示信息并执行删除操作
    echo "Deleting files in $target_directory as it has been at least three years."
    find $target_directory -type f -delete
    find $target_directory -type d -empty -delete
    # 更新记录文件为当前日期
    echo $current_date > /path/to/last_execution_date.txt
else
    # 如果不满足条件,输出提示信息并跳过删除操作
    echo "Not yet three years since last execution. Skipping deletion."
fi

2)请确保赋予这个脚本可执行权限:

chmod +x delete_every_three_years.sh

3)然后设置一个 cron 任务每天运行这个脚本:

0 0 * * * /path/to/delete_every_three_years.sh

2、完工

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值