首页 > 解决方案 > Bash 帮助删除嵌套目录

问题描述

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

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

这当前不执行,给出错误 find: missing argument to '-exec'

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

标签: linuxbashshell

解决方案


我根本不会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
' _ {} +

推荐阅读