Why does “local” sweep the return code of a command?

爱⌒轻易说出口 提交于 2019-11-26 05:50:50

问题


This Bash snippet works as I would\'ve expected:

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

But this one, using local, does not:

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

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


回答1:


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

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



回答2:


The return code of the local command obscures the return code of false



来源:https://stackoverflow.com/questions/4421257/why-does-local-sweep-the-return-code-of-a-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!