Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop in makefile

Tags:

linux

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.

like image 530
Laser Avatar asked May 22 '14 13:05

Laser


2 Answers

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
like image 191
MadScientist Avatar answered Nov 13 '22 07:11

MadScientist


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; \
like image 44
Matthias Avatar answered Nov 13 '22 06:11

Matthias