我试图得到与&&链接的最后一个命令的退出代码和||正确.
我遇到了一个我无法解释的奇怪行为.请帮忙.
gdubicki@mbp-greg:~ $cat exit-code.sh #!/bin/bash echo "running exit-code with $1" exit $1
这按预期工作:
gdubicki@mbp-greg:~ $./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 gdubicki@mbp-greg:~ $(./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
但:
gdubicki@mbp-greg:~ $/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?
原因是使用双引号,在将参数传递给新的Bash进程之前执行参数扩展(特殊参数$?).如果打开调试和详细模式,您可以清楚地看到:
$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
在这种情况下$?设置为0,因为上一个命令(在此示例中设置-xv)成功执行.