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

前端 未结 5 819
悲&欢浪女
悲&欢浪女 2020-11-29 18:19

I was using \"exit 1\" statement in my bash functions to terminate the whole script and it worked fine:

function func()
{
   echo \"Goodbye\"
   exit 1
}
ech         


        
5条回答
  •  悲哀的现实
    2020-11-29 18:43

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

提交回复
热议问题