0

In Makefile, when I am assigning bash variable to Makefile file, it is not working, empty string is assigned. In below code, variable LINE and variable y are empty.

SHELL = bash
target:
        while read -r CURRENT_LINE; do \
                echo "$$CURRENT_LINE" ; \ ##WORKING FINE, display line by line
                LINE=$(shell echo "$$CURRENT_LINE") ; \ ##NOT WORKING
                echo "line:-$(LINE)" ; \ ##empty
                LINE=$$(CURRENT_LINE) ; \ ##NOT WORKING
                echo "line:-$(LINE)" ; \ ##empty
                y=$(subst :, ,$$CURRENT_LINE) ; \ ##NOT WORKING
                echo "y:- $(y)"; \  ##empty

        done < sample_file.txt ; 
piyush-balwani
  • 524
  • 3
  • 15

1 Answers1

0

The correct solution would be:

        while read -r CURRENT_LINE; do \
                LINE="$${CURRENT_LINE}" ;
                echo "LINE:$${LINE}"; \
        done

You need to distinguish between make variables and bash variables, and understand that make expands make variables before passing strings to the shell.

                echo "$$CURRENT_LINE" ; \ ##WORKING FINE, display line by line
                LINE=$(shell echo "$$CURRENT_LINE") ; \ ##NOT WORKING
                echo "line:-$(LINE)" ; \ ##empty

This has two errors: first, you're running $(shell ...), which starts a new shell when make is parsing the recipe... (notice that this is before the recipe runs, and therefore before CURRENT_LINE is set), so in this shell instance, $CURRENT_LINE will expand to empty. The second issue is that you're doing an echo of $(LINE), which is also expanded at make parse time to make's value of its LINE variable. You would need to use $$LINE, which make would expand to $LINE before passing to the shell, and then the shell would be able to expand to its value of $LINE.

For the next part:

                LINE=$$(CURRENT_LINE) ; \ ##NOT WORKING
                echo "line:-$(LINE)" ; \ ##empty

First line should be LINE=$$CURRENT_LINE or LINE=$${CURRENT_LINE}. Bash treats items in $(...) as commands, not variables. This also has a second error that the echo line echo's $(LINE) is again a make variable, which is empty.

                y=$(subst :, ,$$CURRENT_LINE) ; \ ##NOT WORKING
                echo "y:- $(y)"; \  ##empty

So again this is an order thing -- $(subst ...) is expanded at make parse time (before the recipe is actually passed to shell). What it's doing is it's substituting on the string $CURRENT_LINE, not the expanded version of this. Also, you're printing the make version of $(y) again.

HardcoreHenry
  • 5,909
  • 2
  • 19
  • 44