在foreach中访问变量

时间:2018-08-14 09:34:07

标签: makefile

如何从foreach循环外部访问变量。我想打印记录的索引号。 我的代码。

LIST=$(shell ls)
test:
i=0
@$(foreach k,$(LIST), echo "index $(i) = $k";)


Output desired is like below .  
index 0 = A
index 1 = B
index 2 = C
index 3 = D

1 个答案:

答案 0 :(得分:0)

食谱应由shell命令而不是make语句组成,例如:-

制作文件

LIST := $(shell ls) # This is a make-statement

test:       # This is a target
    @# And this is its recipe...
    @# So write shell commands here...
    @i=0; \
    for f in $(LIST); do \
        echo "index $$i = $$f"; \
        i=$$(expr $$i + 1); \
    done

或者简单地:

test:
    @i=0; \
    for f in $$(ls); do \
        echo "index $$i = $$f"; \
        i=$$(expr $$i + 1); \
    done

运行方式:

$ make
index 0 = A
index 1 = B
index 2 = C
index 3 = D
index 4 = Makefile