模仿Python"for-else"构造

nne*_*neo 15 bash for-else

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)

这更加冗长.

Pau*_*ans 8

您可以在循环列表中放置一个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)


Adr*_*rth 8

介绍类似语法的东西非常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)


dev*_*ull 6

使用子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)

  • 简短又甜蜜.我喜欢. (2认同)
  • 大BUG!如果`x`为假,`xyz`列表永远不会到'yz`!@nneonneo你怎么能接受?! (2认同)
  • 这是我正在使用的:`( for i in xyz ; do [ condition $i ] && echo "Condition $i true" && exit; done ) && echo "Found a match" || echo "没有找到匹配项"`。注意使用 `&& exit` 而不是 `|| exit`,这是在 `x` 为 false 时让它继续的关键。 (2认同)