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 scriptexit
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 scriptexit
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With