首页 > 解决方案 > accessing a variable inside foreach

问题描述

How can I access a variable from outside foreach loop . I want to print index number for the record. my code .

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

标签: makefile

解决方案


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

生成文件

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

推荐阅读