bash – 模仿Python“for-else”结构
发布时间:2020-12-16 01:29:12 所属栏目:安全 来源:网络整理
导读:Python有一个方便的语言功能,称为“for-else”(类似地,“while-else”),如下所示: for obj in my_list: if obj == target: breakelse: # note: this else is attached to the for,not the if print "nothing matched",target,"in the list" 基本上,如果循环
|
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:
( for i in x y z; do
[ condition $i ] && echo "Condition $i true!" || exit;
done ) && echo "All was well!" || echo "Something went wrong!"
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
