Search code examples
for-loopmakefileglobal-variables

Makefile update global variable from for loop


I am trying to update a global variable from for loop in makefile
But it seems not to be working as wanted.

PYHTONPATH := /xyz/something/:/bla/bla/python:${PYTHONPATH}

check:
    @for f in $(shell ls /path_to_dir/ ); do \
        PYHTONPATH+=/path_to_dir/$$f: ; \
        echo $$NEW_PYTHON_PATH ; \ # here it is showing properly
    done
    @echo "${PYHTONPATH}"  # here it prints the older value
    

I need to update the global variable from the for loop.
Any lead will be appreciated.
Thanks in advance :)


Solution

  • Make sure you understand the difference between shell variables and make variables. In the first line of your code snippet you assign a make variable named PYHTONPATH. In the recipe of your check rule you concatenate a string to the shell variable named PYHTONPATH which has nothing to do with the make variable with the same name. As it was probably undefined at the beginning of the for loop, at the end, it will probably store all paths in /path_to_dir/, nothing more. Then your first echo will print the NEW_PYTHON_PATH shell variable (because of the double $$). As it was not defined I do not understand why it would print "properly". You should just get a newline. In your final echo you print the make, unmodified, variable (one $ only). Note that even if you double the $ in this last statement, as it is part of a different recipe, executed by a different shell, it will probably not behave as you expect, it will probably again print only a newline.

    Try this, instead, and get, maybe a better understanding of the difference between shell variables and make variables:

    MAKEVAR := /xyz/something/:/bla/bla/python:${PYTHONPATH}
    
    check:
        @SHELLVAR="$(MAKEVAR)"; \
        for f in /path_to_dir/*; do \
            SHELLVAR+="/path_to_dir/$$f:"; \
            echo "$$SHELLVAR"; \
        done; \
        echo "Final value of SHELLVAR = $$SHELLVAR"
        echo "Value of SHELLVAR in a different shell = $$SHELLVAR"
        echo "Make variable MAKEVAR = $(MAKEVAR)"