有没有写一个中止程序的执行,所以不管怎么叫bash函数的方法吗? [英] Is there a way to write a bash function which aborts the whole execution, no matter how it is called?
问题描述
我是用我的bash功能退出1语句来终止整个脚本,它工作得很好:
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
}
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)
据我所知,我创建了一个子shell和退出1,将取消子shell,而不是主之一....
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).
推荐答案
在什么能的做的,就是注册了 TERM顶级壳
信号退出,然后发送一个 TERM
顶端级别外壳:
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"
那么,你的函数发送 TERM
信号回至顶层壳,其被捕获并使用提供的命令,在这种情况下,退出1
。
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"
.
这篇关于有没有写一个中止程序的执行,所以不管怎么叫bash函数的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!