捕获多行命令的退出代码

捕获多行命令的退出代码

TLDR:如何保存Makefile 中运行时的退出cmd1代码?cmd2cmd1 ; cmd2

更多详情:

cmd1 ; cmd2我在 Makefile 中运行,因为cmd2即使cmd1失败我也想运行。

$?cmd1和为空cmd2。否则,我会使用:cmd1 ; E1=$? ; cmd2 ; E2=$?

我看到人们建议使用a=$(cmd1)将退出代码保存到a,但对我来说a也是空的。

答案1

您需要转义,就好像您希望将其传递到 shell$一样:$$

target:
    cmd1; e1=$$?; cmd2; e2=$$?; echo "cmd1 exited with $$e1, cmd2 with $$e2"; exit "$$(( e1 || e2 ))"
    echo only output if both cmd1 and cmd2 succeeded above
$ make target
cmd1; e1=$?; cmd2; e2=$?; echo "cmd1 exited with $e1, cmd2 with $e2"; exit "$(( e1 || e2 ))"
/bin/sh: 1: cmd1: not found
/bin/sh: 1: cmd2: not found
cmd1 exited with 127, cmd2 with 127
make: *** [Makefile:2: target] Error 1

相关内容