[lug] How does bash "set -e" work?

Jeffrey S. Haemer jeffrey.haemer at gmail.com
Thu Jan 3 08:12:10 MST 2013


Zan,

To support what you're saying, the behavior is a property of the parent,
before it creates the subshells.

Demo 1: Commands in braces don't spawn a new shell, even in a compound
statement.

$ s=top
$ { s=left; } || { s=right; }
$ echo $s
left
$ { s=left; } && { s=right; }
$ echo $s
right

Demo 2: The "ignore errexit in compound statements" behavior has nothing to
do with subshells.

$ set -o | grep errexit
errexit      off
$ { set -e; false; echo left; } || true
left
$ set -o | grep errexit
errexit      on
# BEWARE. If you type 'false' now, the shell will exit, even if ignoreeof
is set.
$ set +e # whew! :-)

So, the shell sees there's a compound statement, obeys the "set -e" inside
the braces, setting the option for the entire shell, but then doesn't act
on it when it hits the *false*.

That all boils down to a punctuation-enhanced version of an earlier demo:

$ set -e; false || true; echo done
done

While in compound statements, "errexit" is ignored.

Zan's helpfully reminding me, and anyone else still reading, that forking a
subshell resets the environment to defaults (except for stuff that's
exported) but other things aren't necessarily reset. (File descriptors
aren't, for example.)  "Am I in a compound statement?" isn't.

The final component in a compound statement *will* obey "set -e", so the
parent also tells the forked child whether it's last.


On Thu, Jan 3, 2013 at 1:51 AM, Zan Lynx <zlynx at acm.org> wrote:

> On 1/2/2013 6:23 PM, Jeffrey S. Haemer wrote:
>
> > Rob deduces from this that the " || " persuades the parent shell to
> > instruct its subshell to ignore the flag, but that that instruction is
> > not passed through the environment. In other words, there's got to be
> > some other, out-of-band information channel to the child process.
>
> The information channel is not very mysterious. A sub-shell is simply a
> fork of the parent shell. There is no exec after the fork. The fork'd
> shell gets a copy of all the variables of the parent. One of these is
> probably a in_pipeline variable of some sort.
> _______________________________________________
> Web Page:  http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: irc.hackingsociety.org port=6667 channel=#hackingsociety
>



-- 
Jeffrey Haemer <jeffrey.haemer at gmail.com>
720-837-8908 [cell], http://seejeffrun.blogspot.com [blog],
http://www.youtube.com/user/goyishekop [vlog]
*פרייהייט? דאס איז יאַנג דינען וואָרט.*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20130103/33309de1/attachment.html>


More information about the LUG mailing list