Vam*_*ire 26 bash local-variables exit-code command-substitution
如果赋值是函数中的局部变量,如何在bash中检查命令替换的退出代码?
请参阅以下示例.第二个是我想检查退出代码的地方.
有人有一个良好的解决方案或正确的解决方案吗?
$ function testing { test="$(return 1)"; echo $?; }; testing
1
$ function testing { local test="$(return 1)"; echo $?; }; testing
0
Run Code Online (Sandbox Code Playgroud)
Chr*_*uma 31
如果查看man文件local
(实际上只是BASH内置手册页),它将被视为自己的命令,它会0
在成功创建局部变量时给出退出代码.所以local
覆盖最后执行的错误代码.
试试这个:
function testing { local test; test="$(return 1)"; echo $?; }; testing
Run Code Online (Sandbox Code Playgroud)
编辑:我继续为你尝试,它的工作原理.