Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in makefile not working

In my makefile I have:

all:
  for i in {20..50000..10} ; do \
    echo "Computing $$i" ;\
  done

Which should print numbers 20, 30, 40, ..., 50000 each on a separate line.

This works under Debian oldstable (GNU Make 4.0, GNU Bash 4.3), but not Debian stable (GNU Make 4.1 and GNU Bash 4.4.12).

Debian stable prints just the string "{20..50000..10}". Why is this? What is the portable way to write this for loop in a makefile?

like image 476
kyticka Avatar asked Jun 12 '26 10:06

kyticka


2 Answers

If you run this at your shell prompt:

/bin/sh -c 'for i in {20..5000..10}; do echo $i; done'

you'll see it doesn't work as you'd hoped. Make always invokes /bin/sh (which should be a POSIX shell) to run recipes: it would be a disaster for portability if it used whatever shell the person invoking the makefile happened to be using.

If you really want to write your makefile recipes in bash syntax, then you have to ask for that explicitly by adding:

SHELL := /bin/bash

to your makefile.

like image 65
MadScientist Avatar answered Jun 14 '26 12:06

MadScientist


Stick with a POSIX-compatible loop:

all:
  i=20; while [ "$$i" -le 50000 ]; do \
    echo "Computing $$i"; i=$$((i + 10));\
  done
like image 26
chepner Avatar answered Jun 14 '26 12:06

chepner