Linux, shell script] 如何通过按文件夹名称搜索动态删除文件夹

Linux, shell script] How to dynamically delete folders by searching by folder name

我正在使用 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 日的文件夹。

只删除数据文件夹中超过一天前创建的文件会很简单,但数据文件夹中不遵循 year/month/day/.. 结构的数据(如上面的 ImportantFolder)不应删除,只应保留午夜后创建的文件夹。 (系统 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

您可以尝试这样的操作:

find /root/data -type d -not -name "ImportantFolder" -mtime +1 -exec rm -rf {} \;

因此,仅搜索目录,不包括“重要文件夹”(未测试)。

这里有一些指导原则:

  1. 使用 GNU date 获取各种日期段
    • 示例:current_year=$(date +%Y) 将为您提供当前年份
  2. 使用this type of code遍历目录,一次一级
    • 示例:for current_dir in /data/*/; do ...
  3. 使用 basename or string modification 仅获取每个项目的目录名称(去除斜线)
    • 示例:current_dir=$(basename "$current_dir")
  4. 在每个级别,检查数字是否低于当前year/month/day(取决于级别)
    • Compare using -lt / -gt
    • 示例:if [ "$current_dir" -lt "$current_year" ]; then ...(将其删除 - 或者做一些日志记录以确保您走上正轨)
  5. 如果数字等于 (-eq) 当前 year/month - 那么您可以循环遍历下一个
    • 示例:for current_dir2 in /data/"$current_dir"/*/; do ...