Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of a sourced Bash script's function

I have a Bash script that is sourced. When this script is sourced, it runs a function in the Bash script. This function should terminate the script if a certain condition is matched. How can this be done without terminating the shell in which the script is sourced?

To be clear: I want the termination action to be completed by the function in the sourced shell script, not in the main body of the sourced shell script. The problems that I can see are that return simply returns from the function to the main of the script while exit 1 terminated the calling shell.

The following minimal example illustrates the problem:

main(){
    echo "starting test of environment..."
    ensure_environment
    echo "environment safe -- starting other procedures..."
}

ensure_environment(){
    if [ 1 == 1 ]; then
        echo "environment problemm -- terminating..."
        # exit 1 # <-- terminates calling shell
        return   # <-- returns only from function, not from sourced script
    fi
}

main
like image 695
d3pd Avatar asked Nov 24 '15 13:11

d3pd


People also ask

How do you break a function in bash?

We use exit to exit from a Bash script. In that case, the script exits with the exit status set to the integer argument. If we don't pass an argument to exit, it exits with the exit status set to the exit status of the last command executed before exit.

How do you break out of a while loop in bash?

Breaking from a while LoopUse the break statement to exit a while loop when a particular condition realizes. The following script uses a break inside a while loop: #!/bin/bash i=0 while [[ $i -lt 11 ]] do if [[ "$i" == '2' ]] then echo "Number $i!" break fi echo $i ((i++)) done echo "Done!"

How do I stop a bash script execution?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.

How do you exit a function in Unix shell script?

exit exits the calling shell or shell script with the exit status specified by n . If you omit n , the exit status is that of the last command executed (an end-of-file exits the shell). return exits a function with the return value specified by n . If you omit n , the return status is that of the last command executed.


1 Answers

You can return from a sourced shell script. POSIX spec

So, while you can't return from the function directly to get what you want you can return from the main body of the script if your function returns non-zero (or some other agreed upon value).

For example:

$ cat foo.sh
f() {
    echo in f "$@"
}

e() {
    return 2
}

f 1
e
f 2
if ! e; then
    return
fi
f 3
$ . foo.sh
in f 1
in f 2
like image 95
Etan Reisner Avatar answered Sep 27 '22 22:09

Etan Reisner