Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash functions ignore set -e

Tags:

linux

bash

How can I run a function as a "tested command" and perform action on failure, while still aborting the function as soon as an error occur? Consider the following script

#!/bin/bash -e

function foo() {
   echo Entering foo
   false
   echo Should not reach this line
}

foo || echo I want to see this line on failure in foo
foo

The output I'm getting is

Entering foo
Should not reach this line
Entering foo

While I would like to get

Entering foo
I want to see this line on failure in foo
Entering foo

I guess what I'm looking for is a way to mark the function as untested command. According bash man page

 -e errexit
         Exit immediately if any untested command fails in non-interactive
         mode.  The exit status of a command is considered to be explicitly
         tested if the command is part of the list used to control an if,
         elif, while, or until; if the command is the left hand operand of
         an “&&” or “||” operator; or if the command is a pipeline preceded
         by the ! operator.  If a shell function is executed and its exit
         status is explicitly tested, all commands of the function are con‐
         sidered to be tested as well.

EDIT The expected output was wrong. edited it for clarity

like image 388
Tzafrir Avatar asked Sep 20 '25 11:09

Tzafrir


1 Answers

set -e is disabled in the first call of foo since it's on the left hand side of ||.

Also, you would never see the I want to see this ... string being outputted, unless the last echo in foo somehow failed (it's that last echo in foo that determines the exit status of the function).

foo() {
    echo Entering foo
    false && echo Should not reach this line
}

foo || echo I want to see this line on failure in foo
foo

The above outputs (with or without set -x)

Entering foo
I want to see this line on failure in foo
Entering foo

Now false is the last executed statement in foo.

like image 170
Kusalananda Avatar answered Sep 23 '25 00:09

Kusalananda