[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: return from function doesn't work when used in tail of pipeline
From: |
Martin Schwenke |
Subject: |
Re: return from function doesn't work when used in tail of pipeline |
Date: |
Fri, 13 Aug 2010 09:49:19 +1000 |
On Thu, 12 Aug 2010 08:16:21 -0400, Greg Wooledge <wooledg@eeg.ccf.org>
wrote:
> You already know the reason it behaves the way it does, so I'm not
> quite sure what answer you expect to receive. It's not a bug -- it's
> the normal behavior of every shell.
>
> imadev:~$ sh -c 'f() { (return 0); return 1; }; f; echo $?'
> 1
> [...]
> A return that's run in a subshell doesn't cause the parent shell to
> return.
I want it to either obey the principle of least surprise or be more
clearly documented! return is syntax so I expect it to do what its
documentation says it does...
I've been programming in shell for 20 years and this one surprised me.
I have a very strong Unix background and I clearly understand things
like not being able to set variables in subshells. It also surprised
other people, with similar backgrounds, who I showed it to. It is much
less obvious than many other shell subtleties.
There are some obvious exceptions to the strict Unix subprocess model in
shell programming (e.g. I can set a variable without exporting it and
see it in a subshell) and I expected this to be one of them.
Adding something like this to the documentation for return would
probably be enough:
Note that many compound commands that might be used in a function
cause subshells to be created. In this subshells return will behave
as though it is being used outside a function.
> Use a process substitution in bash:
>
> f() {
> while IFS= read -r somevar; do
> [[ $somevar = *quit* ]] && return 0
> printf '%s\n' "$somevar"
> done < <(grep foo bar)
> return 1
> }
[...]
> The process substitution doesn't require cmd to finish before it
> starts producing data. It's equivalent to a pipeline, except that
> the reader doesn't need to be in a subshell.
Thanks, I'll use that unless I can come up with something more
portable! :-)
peace & happiness,
martin