I was using the "exit 1" statement in my Bash functions to terminate the whole script and it worked fine:
function func() { echo "Goodbye" exit 1 } echo "Function call will abort" func echo "This will never be printed"
But then I realized that it doesn't do the work when called like:
res=$(func)
I understand that I created a subshell and "exit 1" aborts that subshell and not the primary one....
But is there a way to write a function which aborts the whole execution, no matter how it is called? I just need to get the real return value (echoed by the function).
If you want to exit the loop instead of exiting the script, use a break command instead of an exit. #!/bin/bash while true do if [ `date +%H` -ge 17 ]; then break # exit loop fi echo keep running ~/bin/process_data done …
A bash function can return a value via its exit status after execution. By default, a function returns the exit code from the last executed command inside the function. It will stop the function execution once it is called. You can use the return builtin command to return an arbitrary number instead.
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 When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
What you could do, is register the top level shell for the TERM
signal to exit, and then send a TERM
to the top level shell:
#!/bin/bash trap "exit 1" TERM export TOP_PID=$$ function func() { echo "Goodbye" kill -s TERM $TOP_PID } echo "Function call will abort" echo $(func) echo "This will never be printed"
So, your function sends a TERM
signal back to the top level shell, which is caught and handled using the provided command, in this case, "exit 1"
.
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