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
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.
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!"
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.
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.
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
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