Makefile:for循环并在出错时中断

Bar*_*rth 4 for-loop makefile

我有一个带有for循环的Makefile.问题是当循环内发生错误时,执行继续进行.

SUBDIRS += $(shell ls -d */ | grep amore)

# breaks because can't write in /, stop execution, return 2
test:
    mkdir / 
    touch /tmp/zxcv

# error because can't write in / but carry on, finally return 0
tests:
    @for dir in $(SUBDIRS); do \
            mkdir / ; \  
            touch /tmp/zxcv ; \ 
    done;
Run Code Online (Sandbox Code Playgroud)

如何在遇到错误时让循环停止?

Mic*_*ild 10

要么|| exit 1为每个可能失败的调用添加一个,要么set -e在规则的开头执行a :

tests1:
    @dir in $(SUBDIRS); do \
      mkdir / \
      && touch /tmp/zxcv \
      || exit 1; \
    done

tests2:
    @set -e; \
    for dir in $(SUBDIRS); do \
      mkdir / ; \
      touch /tmp/zxcv ; \
    done
Run Code Online (Sandbox Code Playgroud)


bob*_*ogo 5

@Micheal 给出了 shell 解决方案。不过,您确实应该使用 make (然后它将与-jn一起使用)。

.PHONY: tests
tests: ${SUBDIRS}
    echo $@ Success

${SUBDIRS}:
    mkdir /
    touch /tmp/zxcv
Run Code Online (Sandbox Code Playgroud)

编辑

目标的可能解决方案clean

clean-subdirs := $(addprefix clean-,${SUBDIRS})

.PHONY: ${clean-subdirs}
${clean-subdirs}: clean-%:
    echo Subdir is $*
    do some stuff with $*
Run Code Online (Sandbox Code Playgroud)

在这里,我使用静态模式规则(good stuff™),因此配方中$*是模式中匹配的任何内容%(在本例中为子目录)。