111

I was using the "exit 1" statement in my Bash functions to terminate the whole script and it worked fine:

function func()
{
   echo "Goodbye"
   exit 1
}
echo "Function call will abort"
func
echo "This will never be printed"

But then I realized that it doesn't do the work when called like:

res=$(func)

I understand that I created a subshell and "exit 1" aborts that subshell and not the primary one; is there a way to write a function which aborts the whole execution, no matter how it is called?

I just need to get the real return value (echoed by the function).

8 Answers 8

127

What you could do, is register the top level shell for the TERM signal to exit, and then send a TERM to the top level shell:

#!/bin/bash
trap "exit 1" TERM
export TOP_PID=$$

function func()
{
   echo "Goodbye"
   kill -s TERM $TOP_PID
}

echo "Function call will abort"
echo $(func)
echo "This will never be printed"

So, your function sends a TERM signal back to the top level shell, which is caught and handled using the provided command, in this case, "exit 1".

7
  • 1
    I was thinking of the C setsid() function, but it doesn't work quite the same way. Updated to not use the setsid command, as it would require us to start a new process.
    – FatalError
    Commented Mar 27, 2012 at 17:09
  • Is it possible to make a general abort() function out of this that exits using the code of the first argument, e.g. abort 2 would do the trap "exit 2" TERM before kill ? Commented Nov 22, 2013 at 20:53
  • @NeilC.Obremski: Sure. It's mainly an issue of how to get the value to propagate back to the top level shell. Probably use a command like tempfile to select a place to store the code in the top shell, then have the shell that's exiting write the code to that file, then just read in the parent's handler.
    – FatalError
    Commented Nov 25, 2013 at 14:34
  • 2
    Seems to not work when there are intervening subshells. See alt solution for bash using set -E here
    – Ron Burk
    Commented May 10, 2015 at 5:18
  • 1
    @PeterMortensen TERM works... why would SIGTERM be better? Commented Mar 14, 2022 at 15:50
57

You can use set -e which exits if a command exits with a non-zero status:

set -e 
func
set +e

Or grab the return value:

(func) || exit $?
8
  • 3
    Interestingly I see a solution. "set -e" in the main script causes any function returning 1 (or exiting with it) to abort the whole execution. Unfortunately "set -e" changes drastically all the behavior and I cannot use it.
    – LiMar
    Commented Mar 27, 2012 at 16:49
  • 1
    You should use (( )) for numerical comparisons. Inside of [ ] -gt, -eq, etc should be used.
    – jordanm
    Commented Mar 27, 2012 at 17:04
  • 23
    or even res=$(func) || exit Commented Mar 27, 2012 at 17:14
  • @glennjackman gets the cookie, I think. that's much cleaner that the garbage I have!
    – brice
    Commented Mar 27, 2012 at 17:15
  • 3
    that kind of defies the spirit of the question. if every function call needs to catch the error itself, there is no point in using exit in the first place. the function could simply return. / however, if set -e is set globally, this does make good sense
    – phil294
    Commented Sep 14, 2017 at 22:41
3

A child process can't force the parent process to close implicitly. You need to use some kind of signaling mechanism. Options might include a special return value, or perhaps sending some signal with kill, something like

function child() {
    local parent_pid="$1"
    local other="$2"
    ...
    if [[ $failed ]]; then
        kill -QUIT "$parent_pid"
    fi
}
2

I guess better is

#!/bin/bash
set -e
trap "exit 1" ERR

myfunc() {
     set -x # OPTIONAL TO SHOW ERROR
     echo "Exit with failure"
     set +x # OPTIONAL
     exit 1
}
echo "BEFORE..."
myvar="$(myfunc)"
echo "AFTER..But not shown"
2
  • 1
    In what way is it better? Commented Feb 28, 2021 at 0:42
  • This doesn't work if myfunc is called like so: echo "hello $(myfunc)" Commented Mar 14, 2022 at 15:37
2

If you just need top be able to bomb out of your scripts from within a function, you can do:

function die () {
    set -e
    /bin/false
}

then elsewhere, within your functions, instead of using "exit", use "die".

0

But is there a way to write a function which aborts the whole execution, no matter how it is called?

No.

I just need to get the real return value (echoed by the function).

You can

res=$(func)
echo $?
0

This works and is "clean" without a lot of extra hoops, make sure the top level function is defined with parenthesis instead of curly braces. This provides 1) immediate exit as well as 2) the exit status is available:

TestExitAllFunctions ()
(
    function FatalError ()
    {
        echo "$1" 1>&2;
        exit 1
    };
    echo "Function call will abort";
    FatalError "Oops, fatal error found, sorry";
    echo "This will never be printed"
)

TestExitAllFunctions
Function call will abort
Oops, fatal error found, sorry

echo $?
1
-2

I think the easiest and cleanest is

kill –TERM $$

Not the answer you're looking for? Browse other questions tagged or ask your own question.