大网数据广告活动
服务器运维问答

Normal shell vs subshell vs "bash -c" last command exit code

· 52CE 我爱测

I am trying to get the exit code of the last command chained with && and || correctly. I encountered a strange behavior that I cannot explain. Please help. This is my exit-code.sh test script: #!/bin/bash echo "running exit-code …

问题原文

原帖链接 · Greg Dubicki · CC BY-SA 4.0

I am trying to get the exit code of the last command chained with && and || correctly.

I encountered a strange behavior that I cannot explain. Please help.

This is my exit-code.sh test script:

#!/bin/bash
echo "running exit-code with $1"
exit $1

This works as expected:

$ ./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: $?
running exit-code with 1
last command exit code: 1

The same with () to run it in a subshell:

$ (./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: $?)
running exit-code with 1
last exit code: 1

But:

$ /bin/bash -c "./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: $?"
running exit-code with 1
last exit code: 0

Why do I get exit code 0 here?

已采纳解答

原帖链接 · Anthony Geoghegan · CC BY-SA 3.0

Why do I get exit code 0 here?

The reason is that with the double quotes, parameter expansion (of the special parameter, $?) is carried out before passing arguments to the new Bash process. If you turn on debug and verbose mode, you can see this clearly:

$ set -xv
$ bash -c "(./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: $?)"
bash -c "(./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: $?)"
+ bash -c '(./exit-code.sh 1 && ./exit-code.sh 2 && ./exit-code.sh 3 || echo last exit code: 0)'
running exit-code with 1
last exit code: 0
$ set +xv

In this case $? is set to 0 because the previous command (set -xv in this example) executed successfully.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-09-08)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0 / CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。