简体   繁体   English

bash:for file in if?

[英]bash: for file in if exists?

So, 所以,

for f in *.c; do echo "That $f is the best C code I have ever seen"; done

if there are no c files, will gladly print 如果没有c文件,很乐意打印

That *.c is the best C code I have ever seen

which is not desirable. 这是不可取的。 Is there an elegant way of fixing/expressing the fact that I want to skip the loop entirely if there are no c files? 如果没有c文件,是否有一种优雅的方法来修复/表达我想完全跳过循环的事实?

Set the nullglob option. 设置nullglob选项。 Then the expansion will be empty if there is no match. 如果没有匹配,则扩展将为空。

shopt -s nullglob
for f in *.c; do …

Note that this is a bash-specific construct, it won't work under plain sh . 请注意,这是一个特定于bash的构造,它在普通sh下不起作用。

n=`ls -1 *.c 2> /dev/null | wc -l`
if [ $n != 0 ]
then
    for f in *.c; do echo "That $f is the best C code I have ever seen"; done
fi

In Bash, shopt -s nullglob will cause globs which do not match any files to return an empty expansion, rather than identity. 在Bash中, shopt -s nullglob将导致与任何文件不匹配的globs返回空扩展,而不是标识。

For POSIX, maybe something like 对于POSIX,也许是类似的东西

case *.c in '*.c' ) echo no match ;; esac

with the obvious pathological exception that you might separately need to check if there is a single matching file whose name is literally *.c . 有明显的病态异常,您可能需要单独检查是否存在名称字面为*.c的单个匹配文件。

Try: 尝试:

for f in `ls -1 *.c`; do
 echo That $f is the best C code I have ever seen
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM