在bash中,如何在使用本地时检索子shell的退出代码

ope*_*ion 4 exit subshell exit-status

这个问题与其他问题很接近 -我可以从使用 $(command) 启动的子 shell 中获取退出代码吗?

但是,我发现没有解决方案可以让我在使用 local 和 eval 时从子 shell 获取退出代码,如本例所示...

test() {
> local WHY="$(eval "echo 'test'"; exit 3)"; echo $?
> }
test
0
Run Code Online (Sandbox Code Playgroud)

sch*_*ily 7

这很简单:不要使用单个命令而是拆分:

test() {
    local why
    why="$(eval "echo 'test'"; exit 3)"; echo $?
}
test
3
Run Code Online (Sandbox Code Playgroud)

问题是这local是一个带有自己的退出代码的内置命令......如果在变量赋值的同时避免使用该命令,则会从子shell中获得退出代码。