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"
Run Code Online (Sandbox Code Playgroud)
本质上,else如果循环中断,则跳过,但如果循环通过条件失败(for while)或迭代结束(for )退出,则运行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
Run Code Online (Sandbox Code Playgroud)
这更加冗长.
您可以在循环列表中放置一个sentinel值:
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
Run Code Online (Sandbox Code Playgroud)
介绍类似语法的东西非常hacky:
#!/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
Run Code Online (Sandbox Code Playgroud)
$ ./t.sh a
$ ./t.sh d
nothing matched
Run Code Online (Sandbox Code Playgroud)
使用子shell:
( 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"
Run Code Online (Sandbox Code Playgroud)