Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash exit script from inside a function

Tags:

linux

bash

There are situations where you want to terminate the script from inside a function:

function die_if_fatal(){
    ....
    [ fatal ] && <termination statement>
}

If the script is sourced, $ . script, and the termination statement is:

  • return, as expected, will return from die, but will not finish the script
  • exit terminate the session (doesn't return to the script).

Now, if the script is executed: chmod +x script; ./script:

  • return, as expected, will return from die, but will not finish the script
  • exit doesn't return to die and terminate the script.

The simple method is to use return codes and check them upon return, however, I need to stop the parent, without modifying the caller script.

There are alternatives to handle this, however, imagine you are 5 level into a complex script and you find that the script must end; maybe a 'magic' exit code? I just want the execute behavior on a sourced code.

I'm looking for a simple one statement, to end a running sourced script.

When sourcing, what is the right method to finish the script from inside a function?

like image 905
fcm Avatar asked Oct 30 '22 20:10

fcm


1 Answers

Assuming that your script will NOT be sourced from inside a loop you can enclose the main body of your script into an artificial run-once loop and break out of the script using the break command.

Formalizing this idea and providing a couple of supporting utilities, your scripts will have to have the following structure:

#!/bin/bash

my_exit_code=''
bailout() {
    my_exit_code=${1:-0}

    # hopefully there will be less than 10000 enclosing loops
    break 10000
}

set_exit_code() {
    local s=$?
    if [[ -z $my_exit_code ]]
    then
        return $s
    fi
    return $my_exit_code
}

###### functions #######

# Define your functions here.
#
# Finish the script from inside a function by calling 'bailout [exit_code]'

#### end functions #####

for dummy in once;
do

    # main body of the script
    # 
    # finish the script by calling 'bailout [exit_code]'

done
set_exit_code
like image 106
Leon Avatar answered Nov 11 '22 17:11

Leon