Exit code of command substitution in bash local variable assignment [duplicate]

前提是你 提交于 2019-12-04 15:19:03

问题


How can I check the exit code of a command substitution in bash if the assignment is to a local variable in a function?
Please see the following examples. The second one is where I want to check the exit code.
Does someone have a good work-around or correct solution for this?

$ function testing { test="$(return 1)"; echo $?; }; testing
1
$ function testing { local test="$(return 1)"; echo $?; }; testing
0

回答1:


If you look at the man file for local (which is actually just the BASH builtins man page), it is treated as its own command, which gives an exit code of 0 upon successfully creating the local variable. So local is overwriting the last-executed error code.

Try this:

function testing { local test; test="$(return 1)"; echo $?; }; testing

EDIT: I went ahead and tried it for you, and it works.



来源:https://stackoverflow.com/questions/9524623/exit-code-of-command-substitution-in-bash-local-variable-assignment

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