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,但如果循环通过条件失败(对于while)或迭代结束(对于for)退出,则会运行。
在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更详细的是。
发布于 2013-08-27 14:38:51
使用子subshell:
( for i in x y z; do
[ condition $i ] && echo "Condition $i true" && exit;
done ) && echo "Found a match" || echo "Didn't find a match"发布于 2013-08-27 14:19:56
您可以在循环列表中放置一个前哨值:
for i in x y z 'end-of-loop'; do
if [ condition $i ]; then
# loop code goes here
break
fi
if [ $i == 'end-of-loop' ]; then
# your else code goes here
fi
done发布于 2013-08-27 14:29:55
引入类似语法的非常麻烦的东西:
#!/bin/bash
shopt -s expand_aliases
alias for='_broken=0; for'
alias break='{ _broken=1; break; }'
alias forelse='done; while ((_broken==0)); do _broken=1;'
for x in a b c; do
[ "$x" = "$1" ] && break
forelse
echo "nothing matched"
done$ ./t.sh a
$ ./t.sh d
nothing matchedhttps://stackoverflow.com/questions/18467890
复制相似问题