Sergei Shumilin
Sergei Shumilin

Reputation: 431

Execute two commands under condition in for loop in makefile

Code in my MakeFile:

for i in $(SUBDIRS); do \
($(MAKE) -C $$i) || (exit $$? && rm -rf bin);  \
done

If an error in submakes occurs I need to delete the bin directory. How to execute it together, i.e. how to launch exit $$? and rm -rf bin simultaneously? Now only exit $$? is executed.

Upvotes: 0

Views: 516

Answers (1)

Nick ODell
Nick ODell

Reputation: 25409

  1. Save the return code before you call either rm or exit.
  2. Running exit inside a () will not exit, because it is running in a subshell. Use {}. See https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html (This page is for bash, but sh is the same in this way.)

Example:

SUBDIRS := $(wildcard */.)

all:
    @for i in $(SUBDIRS); do \
        $(MAKE) -C $$i || { RETVAL=$$?; rm -rf bin; exit $$RETVAL; }; \
    done

Upvotes: 1

Related Questions