简体   繁体   中英

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

Let's imagine I have a bash script, where I call this:

bash -c "some_command"
do something with code of some_command here

Is it possible to obtain the code of some_command ? I'm not executing some_command directly in the shell running the script because I don't want to alter it's environment.

$? 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).

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

$ 
-bash: exit: a: numeric argument required 255
$ 
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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM