0

I have a complicated script c.sh that tests some part of the environment of the machine make is running. It should be run using bash. It prints some useful information for the use to stdout and stderr. If some special condition is met, c.sh exists with exit code 1, otherwise 0. Other exit codes might occur if something goes wrong. Depending on the exit code, I want to execute different recipes.

all:
    # test using c.sh

everything-OK: # prerequisites
    # *recurse* on this if c.sh exits with zero
    # e.g. "$(MAKE) everything-OK" in all if ...

something-went-wrong: # prerequisites
    # *recurse* on this if c.sh exists with anything else

I have found this useful answer but it does not quite help. Since I cannot seem to get the recursion working or the if switch depending on the exit code. Using $(.SHELLSTATUS) looked promising at first, but that solution does not redirect stdout from the script immediately.

An alternative solution might look like this:

EVERYTHING_OK = 0 # 0: false, 1: true

all:
    # test using c.sh
    # set EVERYTHING_OK depending on exit code
    $(MAKE) second-stage

ifeq (1,EVERYTHING_OK)
second-stage: # prerequisites
    # ...
else
second-stage: # prerequisites
    # ...
endif

(I prefer this, since I can put the if condition in a macro)

HerpDerpington
  • 3,751
  • 4
  • 27
  • 43

1 Answers1

1

If you are interested only in the exit status of your script the easiest is probably to capture it in a make variable and use it in make conditionals or target names. Example with target names:

C_EXIT_STATUS := $(shell ./c.sh &> /dev/null; echo $$?)

.PHONY: all everithing-%

all: everything-$(C_EXIT_STATUS)

everything-0:
    @echo "all right"

everything-%:
    @echo "not all right ($*)"

And then, if ./c.sh exits with status 0:

$ make all
all right

While if it exits with status 7:

$ make all
not all right (7)

Example with make conditionals:

C_EXIT_STATUS := $(shell ./c.sh &> /dev/null; echo $$?)

.PHONY: all

ifeq ($(C_EXIT_STATUS),0)
all:
    @echo "all right"
else
all:
    @echo "not all right ($(C_EXIT_STATUS))"
endif

And last but not least, as you suggested yourself, recursive make is also an option:

.PHONY: all

ifeq ($(C_EXIT_STATUS),)
all:
    s=0; ./c.sh &> /dev/null || s=$$?; \
    $(MAKE) C_EXIT_STATUS=$$s
else ifeq ($(C_EXIT_STATUS),0)
all:
    @echo "all right"
else
all:
    @echo "not all right ($(C_EXIT_STATUS))"
endif
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51