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

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

问题描述

这猛砸段工程,我所期望的:

This Bash snippet works as I would expect:

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

但是这样一来,使用本地,不会:

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

任何人都可以解释这种现象?

Can anyone explain this behavior?

推荐答案

究其原因,code。与本地返回0,是因为 $ ?扩展为最近执行的前台管道的退出状态。因此, $?正在恢复的成功本地

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 像这样解决这个问题p>

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

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

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