Search code examples
makefile

Makefile: Execute several commands, ignore errors and return exit code


I have a Makefile in which I would like to run several commands and ignore error. However, the make target will fail if one of the commands fail. I am running this Makefile on Mac, Ubuntu, and Redhat, so the versions of make are different. I believe the lowest version is 3.8.

Currently, my solution is:

target:
    RC1=0; RC2=0; RC3=0; \
    command1; \
    RC1=$$?; \
    command1=2; \
    RC2=$$?; \
    command3; \
    RC3=$$?; \
    if [ $$RC1 -ne 0 ] || [ $$RC2 -ne 0 ] || [ $$R3 -ne 0 ]; then \
          RC=1; \
    fi; \
    exit $$RC

The problem is at the end with the if statement: Later, I might insert more commands, command4, command5, ... and the if statement will be very clunkly. Is there a simpler solution?

I wish if I can do something like this:

target:
    -command1
    -command2
    -command3
    # Exit with non-zero code if one of the command failed

Solution

  • I don't see any point in keeping all these individual error codes. Why not just use:

    target:
            RC=0; \
            command1 || RC=1; \
            command1 || RC=1; \
            command3 || RC=1; \
            exit $$RC
    

    I can't think of a simpler way than that though.