Is it possible to get the exit code from a subshell?

亡梦爱人 提交于 2019-12-03 04:31:08
Matti Virkkunen

$? will contain the return code of some_command just as usual.

Of course it might also contain a code from bash, in case something went wrong before your command could even be executed (wrong filename, whatnot).

Dennis Williamson

Here's an illustration of $? and the parenthesis subshell mentioned by Paggas and Matti:

$ (exit a); echo $?
-bash: exit: a: numeric argument required
255
$ (exit 33); echo $?
33

In the first case, the code is a Bash error and in the second case it's the exit code of exit.

You can use the $? variable, check out the bash documentation for this, it stores the exit status of the last command.

Also, you might want to check out the bracket-style command blocks of bash (e.g. comm1 && (comm2 || comm3) && comm4), they are always executed in a subshell thus not altering the current environment, and are more powerful as well!

EDIT: For instance, when using ()-style blocks as compared to bash -c 'command', you don't have to worry about escaping any argument strings with spaces, or any other special shell syntax. You directly use the shell syntax, it's a normal part of the rest of the code.

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