为什么“本地"扫描命令的返回码? [英] Why does "local" sweep the return code of a command?

查看:31
本文介绍了为什么“本地"扫描命令的返回码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 Bash 片段按预期工作:

This Bash snippet works as expected:

$ fun1() { x=$(false); echo "exit code: $?"; }
$ fun1
exit code: 1

但是这个使用 local 并没有像我预期的那样:

But this one, using local, does not as I would have expected:

$ fun2() { local x=$(false); echo "exit code: $?"; }
$ fun2
exit code: 0

谁能解释一下为什么local会扫描命令的返回码?

Can anyone explain why does local sweep the return code of the command?

推荐答案

local 的代码返回 0 的原因是因为 $? "展开到退出状态最近执行的前台管道."因此 $? 返回 local

The reason the code with local returns 0 is because $? "Expands to the exit status of the most recently executed foreground pipeline." Thus $? is returning the success of local

您可以通过将 x 的声明与 x 的初始化分开来修复此行为,如下所示:

You can fix this behavior by separating the declaration of x from the initialization of x like so:

$ fun() { local x; x=$(false); echo "exit code: $?"; }; fun
exit code: 1

这篇关于为什么“本地"扫描命令的返回码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆