在迭代目录中的文件时,如下所示
for f in *.txt; do
...
done
Run Code Online (Sandbox Code Playgroud)
即使没有找到符合指定条件的文件,循环也会执行一次.避免这种错误进入循环的最佳方法是什么?可以将条件作为循环中的第一个语句放置,如果f未定义则触发循环中断,但也许有更好的解决方案.
启用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
Run Code Online (Sandbox Code Playgroud)If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |