【发布时间】:2023-04-01 15:18:01
【问题描述】:
我正在使用centOS8,我正在编写一个批处理脚本来删除前一天的数据。
需要删除的文件夹结构如下。
root/data/year/month/day/uuid/time
例如:
root
└ data
└ ImportantFolder
└ 2020
└ 2021
└ 11
└ 12
└ 1
└ 2
└ 550e8400-e29b-41d4-a716-446655440000
└ 2243010332.d
脚本每天凌晨 2:00 运行,并且应该只删除前一天的数据。
例如,如果今天是 2022 年 1 月 1 日,则应删除截至 2021 年 12 月 31 日的文件夹。
只删除数据文件夹中超过一天前创建的文件很简单,但数据文件夹中不遵循年/月/日/..结构的数据(如上面的重要文件夹)不应该被删除,只应保留午夜之后创建的文件夹。 (系统 24/7 全天候工作)
所以,脚本执行的时候,我在想是否可以得到昨天的日期,分解日月年,然后通过条件语句删除。 我是 shellscript 的新手,所以我不知道这是否可能。你能帮我出一个更好的主意,或者我如何用脚本来获取和反汇编前一天的内容吗?
我参考答案中的指南编写的脚本如下。这是一个初学者的脚本,但我希望它可以帮助某人。
#!/bin/bash
function rm_Ymd_forder(){
current_year=$(($(date +%Y)))
current_month=$(($(date +%m)))
current_day=$(($(date +%d)))
base_dir=/data
for current_dir in "$base_dir"/*/; do
current_dir=$(basename "$current_dir")
if [ "$current_dir" -lt "$current_year" ];
then
rm -rf "$base_dir"/"$current_dir"
echo "$base_dir"/"$current_dir" "Deleted"
fi;
done
for current_dir2 in "$base_dir"/"$current_year"/*/; do
current_dir2=$(basename "$current_dir2")
if [ "$current_dir2" -lt "$current_month" ];
then
rm -rf "$base_dir"/"$current_year"/"$current_dir2"
echo "$base_dir"/"$current_year"/"$currnet_dir2" "Deleted"
fi;
done
for current_dir3 in "$base_dir"/"$current_year"/"$current_month"/*/; do
current_dir3=$(basename "$current_dir3")
if [ "$current_dir3" -lt "$current_day" ];
then
rm -rf "$base_dir"/"$current_year"/"$current_month"/"$current_dir3"
echo "$base_dir"/"$current_year"/"$current_month"/"$current_dir3" "Deleted"
fi;
done
}
(
set -e
rm_Ymd_forder
)
errorCode=$?
if [ $errorCode -ne 0 ]; then
echo "Error"
exit $errorCode
else
echo "OK"
exit 0
fi
【问题讨论】: