如何一次返回两个功能?

问题描述 投票:1回答:2

我想写函数abort做一些工作人员然后中止调用函数。可能吗?

目标是模仿set -e,但在功能级别 - 从函数返回而不是退出整个脚本。所以我需要把陷阱放在会杀死功能的ERR上。

可能吗?

bash return
2个回答
4
投票

当程序退出非零时,您可以利用子壳允许它们“击中”。

将函数调用包装在括号中以在子shell中执行它。像这样的东西

#!/bin/bash

function abort {
    set -e
    exit 1
}

function f {
    echo "Hello"
    abort
    echo "Will not be called"
}

(f)
echo "After f"

如果你希望你的f总是“可以中止”,请将整个定义包装在括号中,然后每次调用时都不需要它们:

function f {(
    echo "Hello"
    abort
    echo "Will not be called"
)}

0
投票

听起来你只想在RETURN上找一个陷阱:

$ cat a.sh
#!/bin/bash

cleanup()  {
        echo 'foo invoked cleanup'
}

foo() {
        trap cleanup return
        test "$1" = fail && return 3 # instead of abort
        trap : return # clear the trap to avoid calling cleanup
        return 0
}
foo
echo foo returned $?
foo fail
echo foo returned $?
$ ./a.sh
foo returned 0
foo invoked cleanup
foo returned 3
© www.soinside.com 2019 - 2024. All rights reserved.