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

发布于 2024-08-27 06:53:56 字数 250 浏览 10 评论 0原文

假设我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

书信已泛黄 2024-09-03 06:53:56

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

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

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

野の 2024-09-03 06:53:56

下面是 $? 以及 PaggasMatti 提到的括号子 shell 的说明:

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

在第一种情况下,代码是一个 Bash 错误,并且在第二种情况是exit的退出代码。

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.

断念 2024-09-03 06:53:56

您可以使用 $? 变量,请查看 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.

我ぃ本無心為│何有愛 2024-09-03 06:53:56

我想你正在寻找

$ RESULT=`echo Hello; exit 33`; echo ${PIPESTATUS}; echo $RESULT
33
Hello

I think you're searching for

$ RESULT=`echo Hello; exit 33`; echo ${PIPESTATUS}; echo $RESULT
33
Hello
忆依然 2024-09-03 06:53:56

一些示例代码

cat /etc/passwd | grep -q ubuntu

if [[ "$?" == "0" ]] ; then
  echo "User found"
  exit
fi

echo "User not found"
exit

Some sample code

cat /etc/passwd | grep -q ubuntu

if [[ "$?" == "0" ]] ; then
  echo "User found"
  exit
fi

echo "User not found"
exit
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文