【问题标题】:Bash help deleting nested directoriesBash 帮助删除嵌套目录
【发布时间】:2019-10-15 07:22:16
【问题描述】:

好吧,这听起来可能很奇怪,但我有一个目录 /PDB/ 我想扫描所有包含的目录。所有这些目录都包含几个文件和一个子目录名称 /pockets/,它可能为空,也可能不为空。我想删除每个父目录及其包含空 /pockets/ 子目录的所有内容。到目前为止,我有这个代码:

cd /PDB/
for D in */
do
   find -maxdepth 1 -type d -empty -exec rm -r $D +
done

这当前不执行,给出错误 查找:'-exec' 缺少参数

之前我使用 {} 而不是 $D 但那只删除了空子目录。

【问题讨论】:

  • + 仅在 {} 是它之前立即的参数时才有效。

标签: linux bash shell


【解决方案1】:

我根本不会在这里使用find。考虑:

#!/usr/bin/env bash
#              ^^^^ - NOT /bin/sh; using bash-only features here

shopt -s nullglob           # if no matches exist, expand to an empty list
for d in /PDB/*; do         # iterate over subdirectories
  set -- "$d"/pockets/*     # set argument list to contents of pockets/ subdirectory
  (( "$#" )) && continue      # if the glob matched anything, we aren't empty
  rm -rf -- "${d%/pockets/}"  # if we *are* empty, delete the parent directory
done

...或者,如果您真的想使用find

find /PDB -type d -name pockets -empty -exec bash -c '
  for arg; do
    rm -rf -- "${arg%/*}"
  done
' _ {} +

【讨论】:

  • 好的,这完成了!谢谢!您是否会推荐任何特定资源来学习更详细的 bash 内容,例如您在第一个脚本中使用的内容?
  • Wooledge BashFAQBashGuide(以及其他相关页面 -- f/e BashPitfallsUsingFind)是非常好的资源; bash-hackers' wiki也是如此。
猜你喜欢
  • 2021-04-01
  • 2014-03-01
  • 2018-03-12
  • 2010-10-14
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多