Python有一个方便的语言功能,称为“for-else”(类似地,“while-else”),如下所示:
for obj in my_list: if obj == target: break else: # note: this else is attached to the for,not the if print "nothing matched",target,"in the list"
基本上,如果循环中断,则else被跳过,但如果循环通过条件失败(for while)或迭代结束(for for)退出,则运行else.
有没有办法在bash中做到这一点?最近我想到的是使用一个标志变量:
flag=false for i in x y z; do if [ condition $i ]; then flag=true break fi done if ! $flag; then echo "nothing in the list fulfilled the condition" fi
这是比较冗长的.
使用子shell:
原文链接:https://www.f2er.com/bash/383671.html( for i in x y z; do [ condition $i ] && echo "Condition $i true!" || exit; done ) && echo "All was well!" || echo "Something went wrong!"