Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to write a Bash function which aborts the whole execution, no matter how it is called?

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).

like image 486
LiMar Avatar asked Mar 27 '12 16:03

LiMar


People also ask

What are the ways to get out of a bash loop inside of a script without exiting the actual script?

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 …

How do you terminate a function in bash?

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.

How do you stop a shell script from 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.

What line can you put at the beginning of a bash script to make it so any commands with non zero exit codes immediately stop it?

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.


1 Answers

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

like image 86
FatalError Avatar answered Sep 28 '22 03:09

FatalError