zach
zach

Reputation: 31073

Makefile variable referencing within a nested loop

I am calling a script within a for loop and am running into an issue with variable expansion where the first of two variables is not being included in the output. (note: code adapted from here)

LIST1 := a b c
LIST2 := 1 2 3

all:
    @for x in $(LIST1); do \
      for y in $(LIST2); do\
        echo $$x $$y; \ 
        echo $$x_$$y.txt; \
      done \
    done

#This will output:
a 1
1.txt
a 2
2.txt ....

#Where I expect
a 1
a_1.txt
a 2
a_2.txt

Any ideas on how to get around this issue?

Thanks zach cp

Upvotes: 3

Views: 2161

Answers (1)

MadScientist
MadScientist

Reputation: 101131

This is a shell issue, not a make issue. If you execute x=1; y=a; echo $x_$y.txt you'll see the same output. That's because _ is a valid shell variable name character, so $x_ is a valid shell variable, which is not set. The shell is printing the variable $x_ followed by $y followed by .txt.

Be sure to use braces around your shell variables, if the following character is a valid shell variable name character:

LIST1 := a b c
LIST2 := 1 2 3

all:
        @for x in $(LIST1); do \
          for y in $(LIST2); do\
            echo $$x $$y; \ 
            echo $${x}_$$y.txt; \
          done \
        done

Upvotes: 5

Related Questions