[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] break and continue inside subshells
From: |
Dan Douglas |
Subject: |
Re: [Help-bash] break and continue inside subshells |
Date: |
Sun, 21 Oct 2012 08:06:39 -0500 |
User-agent: |
KMail/4.8.3 (Linux/3.4.6-pf+; KDE/4.8.3; x86_64; ; ) |
On Friday, October 19, 2012 02:13:41 PM Glenn Morris wrote:
>
> Thanks for the helpful answers, everybody.
>
> Dan Douglas wrote:
>
> > The subshell is still aware of its context (being that it's a fork
> > with essentially a copy of the parent environment), it just is
> > isolated from the parent process and can't affect its control flow, so
> > a jump to the end of the subshell seems reasonable.
>
> It doesn't seem that reasonable to me. I could/would have written "exit"
> if I just wanted to jump to the end of the subshell. If I wrote "break",
> then I almost certainly have a bug, and it would be nice if bash warned
> me about it, like it does when there is no containing loop at all.
>
There aren't a lot of alternatives. It's basically either this, or throw an
error. A runtime error produced in a subshell can't cause the script to
terminate for the very same reason -- it's a separate child process.
$ mksh -c 'for _ in 1; do ( break; echo hi; ); echo foo; done'
mksh: break: can't break
hi
foo
If the intention here was to break, you've failed and are still left with a
potential bug. The best recommendation is to not use "break", "continue", or
"return" within subshells. You just have to know where the subshells are.
I personally almost never use explicit subshells. If possible, use functions
and local variables instead. If care is taken, () can be avoided in almost all
situations, especially when not restricted to POSIX-only features.
You might find this example trick (I recently posted to illustrate a bug)
useful in getting local variables in many POSIX shells:
http://article.gmane.org/gmane.comp.programming.tools.ast.devel/651
Also, some people regard "break" and "continue" as a possible indication of
poor programming practice for many of the same reasons as "goto", but that's a
separate and debatable issue.
--
Dan Douglas