当我遍历所有以 foo
开头的文件时,我会这样做
for f in foo* ; do echo "result = $f" ; done
问题是当 no file 以 foo
开头时,我得到:
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/