【问题标题】:Bash: Find any subdirectories without a given file presentBash:查找没有给定文件的任何子目录
【发布时间】:2017-06-25 23:54:13
【问题描述】:

我想知道我的文件是否存在于下面的任何子目录中。子目录是在我的 shell 脚本中的上述步骤中创建的,下面的代码总是告诉我文件不存在(即使它存在),我也希望打印路径。

#!/bin/bash
....

if ! [[ -e [ **/**/somefile.txt && -s **/**/somefile.txt ]]; then
    echo "===> Warn: somefile.txt was not created in the following path: " 
    # I want to be able to print the path in which file is not generated
    exit 1
fi

我知道文件名是 somefile.txt,它将在所有子目录中创建,但子目录名称变化很大.. 因此 globbing。

【问题讨论】:

  • 首先 -- **/somefile.txt 仅扩展为实际存在的 somefile.txt 的副本。如果要查找不存在的目录,则意味着您需要遍历目录,并且不能在 glob 表达式中包含somefile.txt
  • 第二——你不能将 glob 表达式作为参数传递给-e-s;这些测试表达式将一个确切的路径名作为参数,或者一个 single 文件名。它们不采用 glob 或多个文件的列表(在某些情况下,glob 可以扩展到)。
  • 第三,你需要运行shopt -s extglob来使**有任何特殊含义。 (如果您习惯于在交互式 shell 中直接使用它,那么您的一个点文件可能正在为您运行它)。

标签: bash shell subdirectory


【解决方案1】:
#!/bin/bash

shopt -s extglob   ## enable **, which by default has no special behavior

for d in **/; do
  if ! [[ -s "$d/somefile.txt" ]]; then
    echo "===> WARN: somefile.txt was not created (or is empty) in $d" >&2
    exit 1
  fi
done

【讨论】:

  • 这太完美了!非常感谢查尔斯。我真的希望有一些关于此的文档,但这正是我想要的。
  • wiki.bash-hackers.org/syntax/pattern 可能是模式匹配(通配符)文档的一个好起点。 BashFAQ #31 深入讨论了test[[[wiki.bash-hackers.org/syntax/ccmd/conditional_expression 也是一个很好的参考。还有其他内容我可以帮助查找文档吗?
  • FAQ 路径(已经在书签中)和语法模式链接对我有很大帮助。我想我不想要更多我正在做的事情。再次感谢!
猜你喜欢
  • 2015-04-06
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2021-11-28
  • 2021-12-29
  • 1970-01-01
相关资源
最近更新 更多