Using bash variables in Makefile

Lily picture Lily · Apr 7, 2015 · Viewed 16.5k times · Source

I want to use the bash timing variables in my makefile for example in my terminal I can do this and it works

 MY_TIME=$SECONDS 
 echo $MY_TIME

but when I write this on my makefile it does not work

how can I use these two lines in my make file?

this is what I'm doing

.PHONY: myProg
myProg:
      MY_TIME=$SECONDS 
      echo $MY_TIME

After Etan Reisner' answer

This is what I have now

.PHONY: myProg
 myProg:
        MY_TIME= date; echo $MY_TIME

but the result of my echo is an empty line, it does not look like it is storing the date

Answer

Cavaz picture Cavaz · Oct 4, 2019

the dollar sign ($MY_TIME) refers to make variables, which are not the same as bash variables.

To access a bash variable you must escape the dollar using the double dollar notation ($$MY_TIME).

.PHONY: myProg
myProg:
  MY_TIME=$$SECONDS ; echo $$MY_TIME

As already mentioned in Etan answer you can't split the code into multiple lines (unless you are using the backslash) since each command executes in a different subshell, making variables inaccessible to other lines.

In the following example the value of SECONDS will be always 0, since it get reset by the spawn of the shell for the second line.

.PHONY: myProg
myProg:      # WRONG
  MY_TIME=$$SECONDS
  echo $$MY_TIME