bash for循环能够进行零迭代

use*_*001 1 bash for-loop

在迭代目录中的文件时,如下所示

for f in *.txt; do
    ...
done
Run Code Online (Sandbox Code Playgroud)

即使没有找到符合指定条件的文件,循环也会执行一次.避免这种错误进入循环的最佳方法是什么?可以将条件作为循环中的第一个语句放置,如果f未定义则触发循环中断,但也许有更好的解决方案.

Eta*_*ner 6

启用nullglobshell设置:shopt -s nullglob.

$ for f in *.txt; do
    echo "$f"
done
*.txt
$ shopt -s nullglob
$ for f in *.txt; do
    echo "$f"
done
Run Code Online (Sandbox Code Playgroud)

来自bah手册页:

了nullglob

   If  set,  bash allows patterns which match no files (see
   Pathname Expansion above) to expand to  a  null  string,
   rather than themselves.
Run Code Online (Sandbox Code Playgroud)