Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a shell environment variable in a makefile?

Tags:

shell

makefile

People also ask

How do I get env variables in Makefile?

Unfortunately, Makefile doesn't automatically have access to the root . env file, which might look something like this. That said, we can include the appropriate environment file in our Makefile . The environment variables are then accessible using the $(VAR_NAME) syntax.

How can I see environment variables in shell?

Under bash shell: To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

Does make use environment variables?

Each time the make command runs, it reads the current environment variables and adds them to its defined macros. Using the MAKEFLAGS macro or the MFLAGS macro, the user can specify flags to be passed to the make command.


If you've exported the environment variable:

export demoPath=/usr/local/demo

you can simply refer to it by name in the makefile (make imports all the environment variables you have set):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:

make DEMOPATH="${demoPath}" …

If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo for the export command.


all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html


if you export the variable in the same script you will need to use two $$ instead of $, if your Makefile is looking Something like this:

target:
        . ./init.sh; \
        echo ${HOMEPATH}:$${FOO};

in init.sh script you export the variable FOO

$ cat ./init.sh
#!/bin/bash
export FOO=foo:

this way when you run make target the env variable HOMEPATH that were defined before the script runs will be displayed only using one $, but the env variable FOO that is exported in same script will need $$ in order to be shown