0

TLDR: How do I save the exit codes of cmd1 and cmd2 when running cmd1 ; cmd2 in a Makefile?

More detail:

I am running cmd1 ; cmd2 in a Makefile because I want cmd2 to run even if cmd1 fails.

$? is empty for cmd1 and cmd2. Otherwise, I would have used: cmd1 ; E1=$? ; cmd2 ; E2=$?.

I have seen people recommend to use a=$(cmd1) to save the exit code to a, but for me a is empty as well.

5
  • 2
    What do you mean $? is empty? cmd1 ; E1=$? ; cmd2 ; E2=$? should definitely work. Are those variables not being set?
    – jesse_b
    Sep 29, 2022 at 13:27
  • @jesse_b indeed the variables are not set (afaik). Running cmd1 ; echo $? ; cmd2 ; echo $? also prints two empty lines. Sep 29, 2022 at 13:37
  • @jesse_b I am calling this within Makefile, but I assume that shouldnt make a difference Sep 29, 2022 at 13:39
  • 1
    I think it might stackoverflow.com/q/16315089/8239155
    – jesse_b
    Sep 29, 2022 at 13:41
  • 2
    ... it would at least need to be $$? to distinguish the shell variable from a make variable Sep 29, 2022 at 13:43

1 Answer 1

1

You need to escape the $ as $$ if you want it to be passed to the 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .