Search code examples
bashmakefileenvironment-variablestiming

Using bash variables in Makefile


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


Solution

  • By default make uses /bin/sh as the shell which executes recipe lines.

    Presumably /bin/sh doesn't support the SECONDS variable.

    You can tell make to use a different shell by assigning a value to the SHELL variable (i.e. SHELL := /bin/bash).

    Doing that will make SECONDS available but will still not allow you to carry a variable value between recipe lines as each recipe line is run in its own shell.

    So to do what you want you would need to write both of those lines on one line or continue the line over the newline.

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

    or

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

    That being said you would almost certainly be better off not doing this and instead using something like date invoked at the start/end of the recipe or time invoked on the command to be timed directly instead.

    .PHONY: myProg
    myProg:
          date
          # Do something
          date
    

    or

    .PHONY: myProg
    myProg:
          time some_command