Laser
Laser

Reputation: 6960

While loop in makefile

I've got following make file:

n ?= 10
all:
    while [[ $${n} -gt 0 ]] ; do \
        echo $$n ; \
        ((n = n - 1)) ; \
    done

And when I'm trying to run it (make), run fails with error:

make: *** [all] Error 1

I can't understand the reason of this fail.
Any help appreciated.

Upvotes: 11

Views: 21725

Answers (2)

MadScientist
MadScientist

Reputation: 100856

Just to note: you are causing your makefile to be extremely non-portable. Make always invokes recipes using /bin/sh. The recipe you've written is actually a bash script and won't work with a POSIX /bin/sh; it will only work on systems which use /bin/bash as /bin/sh. Many (most, depending on how you count them) do not.

You can rewrite:

n ?= 10
all:
        n=$(n); \
        while [ $${n} -gt 0 ] ; do \
            echo $$n ; \
            n=`expr $$n - 1`; \
        done; \
        true

Upvotes: 22

Matthias
Matthias

Reputation: 8180

A rule examines the last return code. If it is nonzero, make raises an error. In your case, the last retrun code is the result of (( n = n - 1)) for n=2, i.e. 1.

To avoid the error, simply modify the line 5 to:

  ((n = n - 1)) || true; \

Upvotes: 3

Related Questions