bashfor-else

Mimicking the Python "for-else" construct


Python has a handy language feature called "for-else" (similarly, "while-else"), which looks like this:

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"

Essentially, the else is skipped if the loop breaks, but runs if the loop exited via a condition failure (for while) or the end of iteration (for for).

Is there a way to do this in bash? The closest I can think of is to use a flag variable:

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

which is rather more verbose.


Solution

  • Using a 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"