[英]Linux, shell script] How to dynamically delete folders by searching by folder name
I'm using centOS8 and I'm writing a batch script to delete data up to the previous day.我正在使用centOS8,并且正在编写一个批处理脚本来删除前一天的数据。
The structure of the folder that needs to be deleted is as follows.需要删除的文件夹结构如下。
root/data/year/month/day/uuid/time
For example:例如:
root
└ data
└ ImportantFolder
└ 2020
└ 2021
└ 11
└ 12
└ 1
└ 2
└ 550e8400-e29b-41d4-a716-446655440000
└ 2243010332.d
The script runs every day at 2:00 AM and should only delete data up to the previous day.该脚本每天凌晨 2:00 运行,并且应该只删除前一天的数据。
For example, if today is January 1, 2022, folders up to December 31, 2021 should be removed.例如,如果今天是 2022 年 1 月 1 日,则应删除截至 2021 年 12 月 31 日的文件夹。
It would be simple to remove only the files created more than a day ago in the data folder, but data that does not follow the year/month/day/.. structure in the data folder(like ImportantFolder above) should not be deleted, and only folder created after midnight should be kept.只删除数据文件夹中超过一天前创建的文件会很简单,但不应删除数据文件夹中不遵循年/月/日/..结构的数据(如上面的重要文件夹),并且只应保留午夜之后创建的文件夹。 (The system works 24/7) (系统 24/7 工作)
So, when the script is executed, I am thinking whether it is possible to get yesterday's date, decompose day, month, and year, and then delete it through a conditional statement.所以,脚本执行的时候,我在想是否可以得到昨天的日期,分解日月年,然后通过条件语句删除。 I'm new to shellscript so I don't know if this is possible.我是 shellscript 的新手,所以我不知道这是否可能。 Can you help me with a better idea or how I can get and disassemble the previous day with a script?你能帮我一个更好的主意,或者我如何用一个脚本来获取和反汇编前一天的内容吗?
You can try something like this:你可以尝试这样的事情:
find /root/data -type d -not -name "ImportantFolder" -mtime +1 -exec rm -rf {} \;
So, searching only directories, excluding the "ImportantFolder" (Not tested).因此,仅搜索目录,不包括“ImportantFolder”(未测试)。
Here are some guidelines for you:以下是一些指导方针:
current_year=$(date +%Y)
will give you the current year示例: current_year=$(date +%Y)
将为您提供当前年份for current_dir in /data/*/; do
示例: for current_dir in /data/*/; do
for current_dir in /data/*/; do
... for current_dir in /data/*/; do
...current_dir=$(basename "$current_dir")
示例: current_dir=$(basename "$current_dir")
if [ "$current_dir" -lt "$current_year" ]; then
示例: if [ "$current_dir" -lt "$current_year" ]; then
if [ "$current_dir" -lt "$current_year" ]; then
... (remove it - or do some logging to start with to make sure you're on track) if [ "$current_dir" -lt "$current_year" ]; then
......(删除它 - 或做一些记录以确保你在轨道上)for current_dir2 in /data/"$current_dir"/*/; do
示例: for current_dir2 in /data/"$current_dir"/*/; do
for current_dir2 in /data/"$current_dir"/*/; do
... for current_dir2 in /data/"$current_dir"/*/; do
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.