【问题标题】:Batch removal (rm -rf) just for existing directories in a subdirectory仅针对子目录中的现有目录批量删除 (rm -rf)
【发布时间】:2021-03-09 04:49:43
【问题描述】:

背景:我编写了一个非常简单的备份删除脚本,它应该删除早于三个版本更新的备份。 这通过始终将我的软件(Ghost CMS)的新安装版本添加到 txt 文件中来工作,并且所有版本都位于同一目录中($GHOSTDIR/versions/3.x.y)。

            nol=$(grep -c . ghostupgradehistory.txt)
            rl=$(echo "$(($nol-3))")
            lc=$(head -$rl ghostupgradehistory.txt)
            kv=$(tail -3 ghostupgradehistory.txt)
            dir=$(ls $GHOSTDIR/versions -d $lc 2> /dev/null)
            if [[ ${dir[@]} ]]; then echo "Delete old versions" && echo $dir && echo "Keep last three versions" && echo $kv
            cd $GHOSTDIR/versions && rm -rf $dir
            fi

ghostupgradehistory.txt 看起来像这样

3.37.1
3.38.0
3.38.1
3.38.2

我遇到的问题是删除已识别过时版本的最后一条命令。它不只是删除那些,而是删除了整个 $GHOSTDIR/versions 文件夹,其中甚至包括最新版本。如何解决这个问题?

【问题讨论】:

  • 为什么不使用 find 和 -not -newer 来引用最新版本?
  • 我总是想保留三个版本作为备份,不管它们有多旧。
  • 好的,所以做同样的事情,但使用最新版本 -3 所以在你的例子中 find -not -newer .3.38.0 -name *.versions. -not -name *.3.38.0 -type d -delete ?
  • 不知道这可能是一个解决方案,但我认为“-name *.versions”。部分不正确,因为没有 .versions。附加到文件夹: cd ghost/versions/ [versions]$ ls 3.37.1 3.38.0 3.38.1 3.38.2
  • 无论如何都要考虑一下。

标签: bash shell batch-processing rm


【解决方案1】:

如果您确定 GHOSTDIR 中只有带有版本名称的目录,则可以使用简单的解决方法。

首先您列出所有反转的目录以在顶部显示最新版本,然后从第 4 行开始跟踪输出。这意味着 3 个最新的仍然隐藏。最后删除它们。

ls你可以修改为按时间排序-t,如果它更相关或保持字母排序。

cd $GHOSTDIR
ls -1rd */ | tail +4 | xargs rm -rf

或(在某些版本上)

cd $GHOSTDIR
ls -1rd */ | tail -n +4 | xargs rm -rf

就是这样。最多保留 3 个目录。

【讨论】:

  • 这在某种程度上可行: dir=$(ls $GHOSTDIR/versions -1rd */ | tail -3) keep=$(ls $GHOSTDIR/versions -1rd */ | head -3) echo "删除旧版本" && echo $dir && echo "保留最后三个版本" && echo $keep cd $GHOSTDIR/versions && ls -1rd */ |尾-3 | xargs rm -rf 但给出了一个奇怪的输出:删除旧版本/home/user/ghost/versions current/content/保持最近三个版本versions//home/user/ghost/versions current/
  • 你以某种方式混合了head -Xtail -X。在我的帖子中,我使用了tail +X+ 是这里的关键。因为如果版本数少于预期,head 将不起作用。 tail - 反之亦然,然后 head。您可能会丢失一些数据。
  • 那是因为我收到的错误信息是 tail +3: tail: „+3“ cannot be open for reading: file or directory not found
  • 啊哈,那么它可能需要不同的语法,例如在 CentOS 上是 tail -n +4
猜你喜欢
  • 2016-07-09
  • 2012-10-05
  • 1970-01-01
  • 2018-01-17
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多