有没有办法编写一个bash函数来中止整个执行,无论它是如何被调用的?

时间:2012-03-27 16:25:47

标签: bash function exit subshell

我在bash函数中使用“exit 1”语句来终止整个脚本并且运行正常:

function func()
{
   echo "Goodbye"
   exit 1
}
echo "Function call will abort"
func
echo "This will never be printed"

但后来我意识到,在调用时它不会起作用:

res=$(func)

据我所知,我创建了一个子shell,“exit 1”中止了子shell而不是主要的....

是否有办法编写一个中止整个执行的函数,无论它是如何被调用的?我只需要获得实际的返回值(由函数回显)。

5 个答案:

答案 0 :(得分:77)

>

>
TERM

因此,您的函数会将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" )捕获并处理该信号。

答案 1 :(得分:32)

您可以使用set -e

set -e func set +e
(func) || exit $?

或者获取返回值:

{{1}}

答案 2 :(得分:1)

但有没有办法编写一个中止整个执行的函数,无论它是如何被调用的?

我只需要获得真实的返回值(由函数回应)。

您可以

res=$(func)
echo $?

答案 3 :(得分:0)

子进程无法强制父进程隐式关闭。您需要使用某种信令机制。选项可能包含特殊的返回值,或者可能使用kill发送一些信号,例如

function child() {
    local parent_pid="$1"
    local other="$2"
    ...
    if [[ $failed ]]; then
        kill -QUIT "$parent_pid"
    fi
}

答案 4 :(得分:0)

我想更好的是

#!/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"