Take the 2-minute tour ×

I want to do something like:

for i in *
    if test -d $i
        cd $i; make clean; make; cd -;

And this works fine, but I want "break" the for-loop in case of a broken build.

Is there a way to do this? Maybe some kind of if-statement, that can check for success of make?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

You can check whether the make has exited successfully by examining its exit code via the $? variable, and then have a break statement:


if [ $? -ne 0 ]; then
share|improve this answer
Interesting, works perfect. Thanks! –  Kiril Kirov Jun 26 '12 at 11:49
With improved rhyming: for i in *; do make $i || break; done –  reinierpost Jun 26 '12 at 16:48
add comment

You can use Make itself to achieve what you're looking for:

SUBDIRS := $(wildcard */.)

all : $(SUBDIRS)

    $(MAKE) -C $@ clean all

Make will break execution in case when any of your target fails.


To support arbitrary targets:

SUBDIRS := $(wildcard */.)  # e.g. "foo/. bar/."
TARGETS := all clean  # whatever else, but must not contain '/'

# foo/.all bar/.all foo/.clean bar/.clean
    $(foreach t,$(TARGETS),$(addsuffix $t,$(SUBDIRS)))


# static pattern rule, expands into:
# all clean : % : foo/.% bar/.%
$(TARGETS) : % : $(addsuffix %,$(SUBDIRS))
    @echo 'Done "$*" target'

# here, for foo/.all:
#   $(@D) is foo
#   $(@F) is .all, with leading period
#   $(@F:.%=%) is just all
    $(MAKE) -C $(@D) $(@F:.%=%)
share|improve this answer
Thanks, but I'll stick with the if-statement, as I don't want to create new makefile or edit the existing ones. –  Kiril Kirov Jun 26 '12 at 11:53
@Kiril, in fact you can use, e.g., heredoc to redirect the code to make, thus eliminating the need to create a Makefile. make -f - <<EOF ... EOF. –  Eldar Abusalimov Jun 26 '12 at 11:57
Sounds interesting. Thanks! +1 for the effort. –  Kiril Kirov Jun 26 '12 at 12:01
@Kiril, you're welcome. –  Eldar Abusalimov Jun 26 '12 at 12:13
How would one separate out the 'all' and 'clean' tasks so that a 'make clean' can be done at the top level? I've tried adding another target but, as it also depends on $(SUBDIRS) it does a make and make clean. –  starfry Feb 27 '13 at 13:54
show 4 more comments

Your Answer


