bash 是否可以从子shell获取退出代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2556103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:06:59  来源:igfitidea点击:

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

bashscriptingexit-code

提问by Geo

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

假设我有一个 bash 脚本,我称之为:

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_commanddirectly in the shell running the script because I don't want to alter it's environment.

是否有可能获得的代码some_command?我没有some_command直接在运行脚本的 shell 中执行,因为我不想改变它的环境。

回答by Matti Virkkunen

$?will contain the return code of some_commandjust as usual.

$?some_command像往常一样包含返回码。

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

当然,它也可能包含来自 bash 的代码,以防在您的命令甚至可以执行之前出现问题(错误的文件名,诸如此类)。

回答by Paused until further notice.

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

这是PaggasMatti$?提到的括号子外壳的说明:

$ (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.

在第一种情况下,代码是 Bash 错误,在第二种情况下,它是exit.

回答by Paggas

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

您可以使用该$?变量,为此查看 bash 文档,它存储最后一个命令的退出状态。

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!

此外,您可能想查看 bash 的括号样式命令块(例如comm1 && (comm2 || comm3) && comm4),它们总是在子shell 中执行,因此不会改变当前环境,而且功能更强大!

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.

编辑:例如,与 bash -c 'command' 相比,使用 () 样式块时,您不必担心使用空格或任何其他特殊 shell 语法转义任何参数字符串。您直接使用 shell 语法,它是其余代码的正常部分。