Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a bash script from a function whose output is captured

Tags:

linux

bash

shell

sh

I want to completely terminate/exit a bash shell script upon error, but using a function error that lets me display a debug output before termination. Now I have the problem that the exit 1 statement inside the error function will not terminate the shell script if the function's output is captured via backticks or $().

Here is my sample script:

    #!/bin/bash

    function error ()
    {
            echo "An error has occured: $1"
            exit 1
    }
    function do_sth ()
    {
            if [ $1 -eq 0 ]; then
                    error "First param must be greater than 0!"
            else
                    echo "OK!"
            fi
    }

    RESULT=`do_sth 0`

    echo "This line should never be printed"

How can I immediately terminate the script in the error() function?

like image 578
Dynalon Avatar asked Mar 31 '26 06:03

Dynalon


1 Answers

The problem with command substitution is, that a subshell is started to execute do_sth. exit 1 then terminates this subshell and not the main bash.

You can work around this by appending || exit $?, which exits with the exit code from the command substitution

RESULT=`do_sth 0` || exit $?

If you want to show the error message, redirect it to stderr

echo "An error has occured: $1" >&2
like image 89
Olaf Dietsche Avatar answered Apr 02 '26 21:04

Olaf Dietsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!