简单的 Bash - 对于 f in *
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12320521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Bash - for f in *
提问by user1610022
Consider this simple loop:
考虑这个简单的循环:
for f in *.{text,txt}; do echo $f; done
I want to echo ONLY valid file names. Using the $f variable in a script everything works great unless there aren't any files of that extension. In the case of an empty set, $f is set to *.text and the above line echos:
我只想回显有效的文件名。在脚本中使用 $f 变量一切正常,除非没有该扩展名的任何文件。在空集的情况下, $f 设置为 *.text 并且上面的行回显:
*.text
*.txt
rather than echoing nothing. This creates an error if you are trying to use $f for anything that is expecting an actual real file name and instead gets *.
而不是什么都不回响。如果您尝试将 $f 用于任何需要实际真实文件名的内容,而是将 *.
If there are any files that match the wildcard so that it is not an empty set everything works as I would like. e.g.
如果有任何文件与通配符匹配,因此它不是空集,那么一切都按我的意愿工作。例如
123.text
456.txt
789.txt
How can I do this without the errors and without seemingly excessive complexity of first string matching $f for an asterisk?
我怎样才能在没有错误的情况下做到这一点,并且没有第一个字符串匹配 $f 的星号看起来过于复杂?
回答by Ignacio Vazquez-Abrams
Set the nullgloboption.
设置nullglob选项。
$ for f in *.foo ; do echo "$f" ; done
*.foo
$ shopt -s nullglob
$ for f in *.foo ; do echo "$f" ; done
$
回答by perreal
You can test if the file actually exists:
您可以测试该文件是否确实存在:
for f in *.{text,txt}; do if [ -f $f ]; then echo $f; fi; done
or you can use the findcommand:
或者您可以使用以下find命令:
for f in $(find -name '*.text' -o -name '*.txt'); do
echo $f
done
回答by ThePadawan
Also, if you can afford the external use of ls, you can escape its results by using
此外,如果您负担得起 的外部使用ls,则可以通过使用来逃避其结果
for f in `ls *.txt *.text`;

