bash - 没有匹配文件时如何跳过for循环?

标签 bash for-loop wildcard shopt

当我遍历所有以 foo 开头的文件时,我会这样做

for f in foo* ; do echo "result = $f" ; done

问题是当 no filefoo 开头时,我得到:

result = foo*

这意味着即使没有以 foo 开头的文件,循环也会执行一次。

这怎么可能?我如何循环遍历所有文件(如果没有文件则根本不循环)?

最佳答案

您可以通过设置 nullglob 来阻止此行为:

shopt -s nullglob

来自链接页面:

nullglob is a Bash shell option which modifies [[glob]] expansion such that patterns that match no files expand to zero arguments, rather than to themselves.

您可以使用 -u 删除此设置(未设置,而 s 用于设置):

shopt -u nullglob

测试

$ touch foo1 foo2 foo3
$ for file in foo*; do echo "$file"; done
foo1
foo2
foo3
$ rm foo*

让我们看看:

$ for file in foo*; do echo "$file"; done
foo*

设置nullglob:

$ shopt -s nullglob
$ for file in foo*; do echo "$file"; done
$

然后我们禁用该行为:

$ shopt -u nullglob
$ for file in foo*; do echo "$file"; done
foo*

关于bash - 没有匹配文件时如何跳过for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26255799/

相关文章:

macos - 自动打开目录 (mac os x) 和创建 m3u 播放列表的脚本

linux - 防止在 bash 中意外编辑历史记录

java - 创建多个子类对象

python - 对列表和多次迭代的误解

java - 对象和抽象的ArrayList

linux - 如何在Bash中将字符串转换为其他字符串?

c++ - 是否有更好的方法来对 unordered_multimap 键进行平均?

java - 嵌套通配符

mysql - 字符类不适用于阿拉伯文本列

Linux,检查当前没有正在运行的 cron 作业的代码?