Bash中的嵌套函数:为什么return会停止父函数?

Bash中的嵌套函数:为什么return会停止父函数?,bash,Bash,我希望函数test\u nok中的return 1只退出嵌套函数{echo”[Error]text;return 1;},并且执行以下两个echo命令,因为它们属于父函数test\u nok 但那不是真的,echo“this not executed”确实没有执行,test_nok的退出代码是1。这是我需要的行为,但我不明白它为什么会这样运行=>为什么echo“This not executed”not executed?您可以将错误代码保存在变量中,并在函数末尾返回它(尽管这可能不是一个好主意

我希望函数
test\u nok
中的
return 1
只退出嵌套函数
{echo”[Error]text;return 1;}
,并且执行以下两个echo命令,因为它们属于父函数
test\u nok


但那不是真的,
echo“this not executed”
确实没有执行,test_nok的退出代码是1。这是我需要的行为,但我不明白它为什么会这样运行=>为什么
echo“This not executed”
not executed?

您可以将错误代码保存在变量中,并在函数末尾返回它(尽管这可能不是一个好主意。我建议在错误发生时返回):

输出:

function test_nok {
    echo "function with error"
    cause-an-error || { error_code=$?; echo "[Error] text"; }
    echo "this is not executed"
    echo "this is not executed"
    return $error_code
}
test_nok
echo $?
在评论中回答了我的问题:


这里没有嵌套函数
{}
不是函数,它只是对命令进行分组。

这里没有嵌套函数<代码>{}不是函数,它只是对命令进行分组。谢谢戈登·戴维森,这回答了我的问题。但我认为我不能将注释标记为解决方案,对吗?如果您只想从“嵌套函数”返回,请使用子shell
(…)
而不是组
{…}
。谢谢。我发布的代码工作起来就像我需要它一样,我只是不明白为什么。但是我认为Gordon Davidson刚刚回答了我的问题=>{}不是一个好函数,关于你的问题
为什么echo“this not executed”没有执行?
你可能想阅读更多关于bash文档:Thank you Sergio的
{…;}
命令的内容,这正是我在最后几分钟所做的:-)这是我的意图,但我得到的信息是“你可以在两天内接受你自己的答案”。所以我会在2天内接受它,或者戈登·戴维森可以写一个我可以接受的答案
function test_nok {
    echo "function with error"
    cause-an-error || { error_code=$?; echo "[Error] text"; }
    echo "this is not executed"
    echo "this is not executed"
    return $error_code
}
test_nok
echo $?
function with error
./test.sh: line 5: cause-an-error: command not found
[Error] text
this is not executed
this is not executed
127