当*.txt
目录中实际存在文件时,以下 bash 代码段效果很好。
for txt in *.txt
do
echo "loading data from $txt"
done
Run Code Online (Sandbox Code Playgroud)
如果没有,文字*.txt
会作为 $txt 进入循环(不好)。
如何更改此代码以便在没有*.txt
文件时do ... done
跳过该块?
kfm*_*e04 13
把这个魔法咒语放在for
语句之前:
shopt -s nullglob
Run Code Online (Sandbox Code Playgroud)
(文档)
nullglob 选项(@kfmfe04 的答案)是最好的,如果您使用的是 bash(不是品牌 X shell),并且不必担心 nullglob 会改变/破坏其他任何东西。否则,您可以使用此(稍微混乱的)选项:
for txt in *.txt
do
[ -e "$txt" ] || continue
echo "loading data from $txt"
done
Run Code Online (Sandbox Code Playgroud)
这会默默地跳过不存在的文件(如果没有匹配项,主要是“*.txt”,但也可能是在for
生成列表和循环到达它们之间删除的文件......)