Skip to content
Advertisement

How can i initialize and then iterate an array in linux makefile?

I need to create an array with directories and then inereate it, creating one more array in each step which will include all files found via ‘find’ command for each derictory and also iterate this array. I was trying to do something like this:

declare -a arr=(a b c) ;
for key in "$${arr[@]}" ; do 
    ...
  done

but it does not work. Even this gets error:

all:
        declare -a array=(a b c) ;
        echo "$${array[1]}" 

gets error:

/bin/sh: 1: Syntax error: "(" unexpected
Makefile:4: recipe for target 'gg' failed
make: *** [gg] Error 2

Advertisement

Answer

This is because make always invokes /bin/sh (POSIX shell) when it runs recipes unless you tell it differently. The syntax you’re using is specific to the /bin/bash shell and not available in /bin/sh.

If you want to run your recipes using /bin/bash you have to specifically tell make to do that by adding this to your makefile:

SHELL := /bin/bash

See For loop in makefile not working for another answer.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement