tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: set -e again



At Wed, 14 Jan 2026 01:18:47 +0000, David Holland <dholland-tech%netbsd.org@localhost> wrote:
Subject: set -e again
>
> I discovered the following today.
>
> This:
>    set -e
>    f() {
>        echo foo
>        false
>        echo bar
>    }
>    f
>
> as one might expect, prints "foo" and exits.
>
> However, this:
>    set -e
>    f() {
>        echo foo
>        false
>        echo bar
>    }
>    f || echo baz
>    echo buzz
>
> prints "foo", "bar", "buzz", and continues. Furthermore, all the
> shells I have in easy reach agree on it.

That makes perfect sense to me.

Note that if the function invocation is not "guarded" by testing its
exit status then execution is terminated after the false statement just
as one would also expect.

Shell functions are effectively macros.

Replace the invocation of f() with its "value" and it now looks like:

	$ set -e
	$ { echo foo; false; echo bar; } || echo baz; echo buzz
	foo
	bar
	buzz
	$ echo $?
	0

Perhaps another way to think about it is that the part wrapped in
brackets is a compound command, and indeed the manual concurs.

A function definition is most simply "f() command", and of course the
"command" part can be either a simple command or a list (i.e. a form of
compound command).

So since the compound command is followed by an operator that tests its
status, the whole compound command is executed in the guarded
environment.

The manual also says:  "The function completes after having executed
_command_ with [[its]] exit status set to the status returned by
_command_." though obviously that statement doesn't take into account an
un-guarded execution of a function in a shell with errexit("set -e") set.

> Is this intended, and is there a way to get the user's intended
> behavior of exit on unchecked failure back? (E.g. is there a different
> set to get functions to return on unchecked failure that might cover
> this?

I would definitely say it is/was intended.

Perhaps as an extension the shell could override the guard if a function
definition includes a call to "set -e" within it.

--
					Greg A. Woods <gwoods%acm.org@localhost>

Kelowna, BC     +1 250 762-7675           RoboHack <woods%robohack.ca@localhost>
Planix, Inc. <woods%planix.com@localhost>     Avoncote Farms <woods%avoncote.ca@localhost>

Attachment: pgpa_oOkQff3G.pgp
Description: OpenPGP Digital Signature



Home | Main Index | Thread Index | Old Index