【问题标题】:What to do to make loop ignore empty directories如何使循环忽略空目录
【发布时间】:2022-11-04 02:31:31
【问题描述】:

我有一个循环,我需要它来忽略空目录。

for i in */*/
do

    cd "$i"
    mv ./*.py ..
    cd -
    rm -r "$i"
done

我可以添加什么使其忽略空目录?

我有这个,但我想要更简单的东西

    x=$(shopt -s nullglob dotglob; echo "$i"/*)
    (( ${#x} )) || continue

【问题讨论】:

  • 通过“忽略”空目录,您的意思是它不仅不应该尝试将.py 文件移出它们,而且也不应该尝试删除它们?
  • 顺便说一句,rm -r "$i" 让我不寒而栗。

标签: bash loops ubuntu unix


【解决方案1】:

我可以添加什么使其忽略空目录?

Bash 没有用于测试目录是否为空的原始运算符。最好的替代方法是测试路径名扩展是否与其中的任何文件匹配。这就是您已经在考虑的内容,尽管我会以不同的方式编写它。

作为一般规则,我也会避免更改工作目录。如果你必须更改目录然后考虑在子shell中进行,这样您只需让子shell终止即可恢复到原始工作目录。当脚本的不同部分需要不同的 shell 选项时,使用子 shell 也是一种好方法。

我可能会这样写你的脚本:

#!/bin/bash

shopt -s nullglob dotglob

for i in */*/; do
  anyfiles=( "$i"/* )
  if [[ ${#anyfiles[@]} -ne 0 ]]; then
    # "$i" is a nonempty directory

    # If there are any Python files within then move them to the parent directory
    pyfiles=( "$i"/*.py )
    if [[ ${#pyfiles[@]} -ne 0 ]]; then
      mv "${pyfiles[@]}" "$(dirname "$i")"
    fi

    # Remove directory "$i" and any remaining contents
    rm -r "$i"
  fi
done

如果您希望将其作为更大脚本的一部分,那么您可以将 shopt 到末尾的所有内容放在子 shell 中,以限制 shopt 的范围。

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 2010-09-12
    • 2013-06-07
    • 2020-05-05
    • 1970-01-01
    • 2019-10-14
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多