考虑下面这个简单的循环:
for f in *.{text,txt}; do echo $f; done我只想回显有效的文件名。在脚本中使用$f变量,除非没有该扩展名的任何文件,否则一切正常。在空集的情况下,将$f设置为*.text,并回显上一行:
*.text
*.txt而不是一言不发。
如果有任何文件与通配符匹配,因此它不是一个空集,那么一切都会按照我所希望的那样工作。例如:
123.text
456.txt
789.txt发布于 2012-09-07 22:59:48
设置nullglob选项。
$ for f in *.foo ; do echo "$f" ; done
*.foo
$ shopt -s nullglob
$ for f in *.foo ; do echo "$f" ; done
$ 发布于 2012-09-07 22:56:43
您可以测试该文件是否确实存在:
for f in *.{text,txt}; do if [ -f $f ]; then echo $f; fi; done或者您可以使用find命令:
for f in $(find -name '*.text' -o -name '*.txt'); do
echo $f
done发布于 2012-09-07 22:58:10
此外,如果您负担得起ls的外部使用,则可以通过使用
for f in `ls *.txt *.text`;https://stackoverflow.com/questions/12320521
复制相似问题