Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make makefile exit with error when using a loop?

Tags:

bash

makefile

If I have the following bash command:

for i in ./ x ; do ls $i ; done && echo OK

"ls ./" is executed, and then "ls x", which fails (x is missing) and OK is not printed.

If

for i in x ./ ; do ls $i ; done && echo OK

then even though "ls x" fails, because the last statement in the for loop succeeded, then OK is printed. This is a problem when using shell for loops in makefiles:

x:
    for i in $(LIST) ; do \
        cmd $$i  ;\
    done 

How can I make make fail if any of the individual executions of cmd fails?

like image 519
user48956 Avatar asked Oct 17 '13 20:10

user48956


2 Answers

Use the break command to terminate the loop when a command fails

x:
    for i in $(LIST) ; do \
        cmd $$i || break ;\
    done 

That won't make the makefile abort, though. You could instead use exit with a non-zero code:

x:
    for i in $(LIST) ; do \
        cmd $$i || exit 1 ;\
    done 
like image 66
Barmar Avatar answered Oct 22 '22 17:10

Barmar


After executing the command, check for return value of that command using $?, as its make file you need to use double $. If its non zero, then exit with failure.

x:
    set -e
    for i in $(LIST); do \
        cmd $$i; \
        [[ $$? != 0 ]] && exit -1; \
        echo 'done'; \
    done
like image 39
rashok Avatar answered Oct 22 '22 18:10

rashok