[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Why should `break' and `continue' in functions not break loops running o
From: |
Oğuz |
Subject: |
Why should `break' and `continue' in functions not break loops running outside of the function? |
Date: |
Sat, 30 Oct 2021 14:39:19 +0300 |
I would expect the following to print only 1 and return,
f() { break; }
for x in 1 2 3; do
echo $x
f
done
because `f' is called from within a loop, and executed in the same
environment as the loop. But it doesn't. It prints all 1, 2, and 3;
and complains about `break' being only meaningful in a loop, which is
confusing to me, because it _is_ in a loop.
I found that this behavior had been introduced in 2014, with the
following commit message:
> set loop_level to 0
> when entering a function so break and continue in functions don't
> break loops running outside of the function. Fix picked up from
> dash
and the commit message for the fix in question reads:
> As it is if you do a multi-level break inside a function it'll actually
> include loops outside of the function call. This is counterintuitive.
No further explanation as to how it is counterintuitive. I think it is
intuitive though; unlike with other languages, `break' is not a
keyword in the shell, but a special command. And its scope, in my
opinion, shouldn't be limited to the function body it is called from.
What is counterintuitive instead is that `break 999' (for example)
breaks the outermost loop unless you have a thousand loops nested, but
`break' (and `continue') breaking across functions is not
counterintuitive at all, it feels far more natural and is far easier
to explain than the behavior implemented now.
So, does anyone know a case where the new behavior can be useful/the
old behavior can be harmful? Am I missing an obvious problem with the
old one?
Oğuz