没有匹配文件时如何跳过for循环? [英] How to skip the for loop when there are no matching files?
问题描述
当我遍历所有以 foo
开头的文件时,我会
When I loop through all the files starting by foo
I do
for f in foo* ; do echo "result = $f" ; done
问题是当 no file 以 foo
开头时,我得到:
The problem is when no file start by foo
I get:
result = foo*
表示循环执行一次,即使没有文件以foo
开头.
Meaning that the loop is executed once, even if no file start by foo
.
这怎么可能?如何遍历所有文件(如果没有文件则根本不循环)?
How is this possible? How can I loop through all files (and not loop at all if there is no file)?
推荐答案
您可以通过设置 nullglob一个>:
shopt -s nullglob
来自链接页面:
nullglob
是一个修改 [[glob]] 扩展的 Bash shell 选项这样不匹配任何文件的模式扩展到零参数,而不是对他们自己.
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
用于设置):
You can remove this setting with -u
(unset, whereas s
is for set):
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*
这篇关于没有匹配文件时如何跳过for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!