What about empty for loops in Makefiles?

What about empty for loops in Makefiles?


It's fairly common to see constructs like this in automatically-generated
Makefiles:

SUBDIRS = @SUBDIRS@

...

subdirs-clean:
for d in ${SUBDIRS}; do \
( cd $$d && ${MAKE} ${MFLAGS} clean ) \
done

When SUBDIRS is empty, this results in a command like this being passed to
bash:

for d in ; do
( cd $d && ${MAKE} ${MFLAGS} clean )
done

In versions of bash before bash-2.05a, this was a syntax error. If the
reserved word `in' was present, a word must follow it before the semicolon
or newline. The language in the manual page referring to the list of words
being empty referred to the list after it is expanded. These versions of
bash required that there be at least one word following the `in' when the
construct was parsed.

The idiomatic Makefile solution is something like:

SUBDIRS = @SUBDIRS@

subdirs-clean:
subdirs=$SUBDIRS ; for d in $$subdirs; do \
( cd $$d && ${MAKE} ${MFLAGS} clean ) \
done

The latest drafts of the updated POSIX standard have changed this: the
word list is no longer required. Bash versions 2.05a and later accept
the new syntax.



Home FAQ