有没有办法编写一个 bash 函数来中止整个执行,无论它如何调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9893667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to write a bash function which aborts the whole execution, no matter how it is called?
提问by LiMar
I was using "exit 1" statement in my bash functions to terminate the whole script and it worked fine:
我在 bash 函数中使用“exit 1”语句来终止整个脚本,它运行良好:
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....
我知道我创建了一个子 shell 并且“exit 1”中止了该子 shell 而不是主要的....
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).
但是有没有办法编写一个中止整个执行的函数,无论它如何调用?我只需要获得真正的返回值(由函数回显)。
回答by FatalError
What you coulddo, is register the top level shell for the TERM
signal to exit, and then send a TERM
to the top level shell:
您可以做的是注册顶级shellTERM
以退出信号,然后将a发送TERM
到顶级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"
.
因此,您的函数将一个TERM
信号发送回顶级 shell,使用提供的命令捕获并处理该信号,在本例中为"exit 1"
.
回答by brice
You can use set -e
which exits if a command exits with a non-zero status:
如果命令以非零状态退出,您可以使用set -e
which exits:
set -e
func
set +e
Or grab the return value:
或者获取返回值:
(func) || exit $?
回答by AmazingAlex
I guess better is
我想更好的是
#!/bin/bash
set -e
trap "exit 1" ERR
myfunc() {
set -x # OPTIONAL TO SHOW ERROR
echo "Exit with failure"
set +x # OPTIONAL
exit 1
}
echo "BEFORE..."
myvar="$(myfunc)"
echo "AFTER..But not shown"
回答by Luca
But is there a way to write a function which aborts the whole execution, no matter how it is called?
但是有没有办法编写一个中止整个执行的函数,无论它如何调用?
No.
不。
I just need to get the real return value (echoed by the function).
我只需要获得真正的返回值(由函数回显)。
You can
你可以
res=$(func)
echo $?
回答by Daenyth
A child process can't force the parent process to close implicitly. You need to use some kind of signaling mechanism. Options might include a special return value, or perhaps sending some signal with kill
, something like
子进程不能强制父进程隐式关闭。您需要使用某种信号机制。选项可能包括一个特殊的返回值,或者可能发送一些信号kill
,例如
function child() {
local parent_pid=""
local other=""
...
if [[ $failed ]]; then
kill -QUIT "$parent_pid"
fi
}