0

here is the minimal code (tested on centos7 bash 4.2 and rocky8 bash 4.4):

#!/bin/bash

func1() {
    echo a
    echo b
    cd asdfasdf123
    echo "c: should not get here"
    echo "d: should not get here"
}

main() {
    echo "DEBUG: $FUNCNAME: LINENO=$LINENO"

    exitcode=0
    func1 || exitcode=1

    echo "DEBUG: $FUNCNAME: LINENO=$LINENO"

    func1

    echo "DEBUG: $FUNCNAME: LINENO=$LINENO"
}

set -x
set -eu
main
  • in the first call of func1: i am expecting the code to never print the echo c line of code. but instead i see that the code does get to the echo c line of code.
  • in the second call of func1: i see that the code does correctly exit when the error happens.

this is bad because i have a larger important shell program that gets an error early in the code and does not exit when i need the code to exit and instead keeps going even though the early operation did not do what i needed it to do.

set -o errexit is not exiting when a command has an error. how do you change this code to make it exit when there is an error?

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
  • 2
    This is intended behavior. See [the manual](https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin). `The shell does not exit if the command that fails is...part of any command executed in a && or || list except the command following the final && or ||`. For this reason and lots of others, it's generally recommended to not use `set -e` and do your own error handling. – tjm3772 Feb 03 '23 at 16:08
  • 2
    See also [BashFAQ/105](http://mywiki.wooledge.org/BashFAQ/105). – tjm3772 Feb 03 '23 at 16:10
  • glad that this behavior is well understand and well documented. i thought i was in uncharted water. i'll have to read all the replies and the duplicate question. – Trevor Boyd Smith Feb 03 '23 at 17:50
  • @tjm3772 your bash FAQ link is amazing. i wish i had read that back in 2010. it also talks about the exact behavior i am seeing **"As soon as a function is used as a conditional (in a list or with a conditional test or loop) set -e stops being applied within the function"**. – Trevor Boyd Smith Feb 03 '23 at 20:19

0 Answers0