[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: set -e not working as expected with conditional operators
From: |
Greg Wooledge |
Subject: |
Re: set -e not working as expected with conditional operators |
Date: |
Fri, 2 Jun 2023 09:24:43 -0400 |
On Fri, Jun 02, 2023 at 09:01:11AM -0400, Chet Ramey wrote:
> On 6/1/23 9:01 PM, rpaufin1 wrote:
> > Consider the following script:
> >
> > #!/bin/bash
> >
> > f() {
> > ls missing-file 2> /dev/null
> > echo "test"
> > }
> >
> > # 1
> > (set -e; f); ret=$?
> > if (( ret )); then
> > echo "failed"
> > exit 1
> > fi
> >
> > # 2
> > (set -e; f) || {
> > echo "failed"
> > exit 1
> > }
> >
> > Running the block labelled '1' prints "failed" and returns 1 as the exit
> > code, while running the other block prints "test" and returns 0. However,
> > the result should be the same.
>
> It should not. The manual lists the instances where the shell does not
> exit if a command fails while -e is enabled, and and-or lists are one of
> those.
It's similar to example 4 on <https://mywiki.wooledge.org/BashFAQ/105>.
People are probably going to be surprised that the call to f in "block 2"
above is considered "part of an and-or list", because the and-or list
appears outside of the subshell. I presume that the subshell inherits
the "I am inside an and-or list" flag from its parent process, and
doesn't clear it, and that this is intentional.
Examples like this continue to demonstrate why set -e should be avoided.