是否可以从子 shell 获取退出代码?
假设我有一个 bash 脚本,我称之为:
bash -c "some_command"
do something with code of some_command here
Is it possible to get the code of some_command
?我没有直接在运行脚本的 shell 中执行 some_command
因为我不想改变它的环境。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
$?
将像往常一样包含some_command
的返回码。当然,它也可能包含来自 bash 的代码,以防在执行命令之前出现问题(文件名错误等)。
$?
will contain the return code ofsome_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).
下面是
$?
以及 Paggas 和 Matti 提到的括号子 shell 的说明:在第一种情况下,代码是一个 Bash 错误,并且在第二种情况是
exit
的退出代码。Here's an illustration of
$?
and the parenthesis subshell mentioned by Paggas and Matti:In the first case, the code is a Bash error and in the second case it's the exit code of
exit
.您可以使用
$?
变量,请查看 bash 文档,它存储最后一个命令的退出状态。另外,您可能想查看 bash 的括号样式命令块(例如
comm1 && (comm2 || comm3) && comm4
),它们始终在子 shell 中执行从而在不改变当前环境的情况下,也更加强大!编辑:例如,与 bash -c 'command' 相比,使用 () 样式块时,您不必担心用空格或任何其他特殊 shell 语法转义任何参数字符串。您可以直接使用 shell 语法,它是其余代码的正常部分。
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.
我想你正在寻找
I think you're searching for
一些示例代码
Some sample code