Jialin
Jialin

Reputation: 2715

How to get a shell environment variable in a makefile?

In shell when I enter

echo $demoPath

it prints

/usr/local/demo

How can I get the value of this variable $demoPath in a makefile?

Upvotes: 223

Views: 361687

Answers (6)

Jonathan Leffler
Jonathan Leffler

Reputation: 753805

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.

Upvotes: 321

FRDe
FRDe

Reputation: 1

if you export the variable in the same script you will need to use two $$ instead of $, if your Makefile is looking Somethithis 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 e

Upvotes: -2

Ali BENALI
Ali BENALI

Reputation: 745

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 init.sh script which is executed inside your make file will need $$ in order to be shown

Upvotes: 17

Dmitry Grinko
Dmitry Grinko

Reputation: 15204

If your .env file is located in the same directory you can use include .env statement:

.env

DEMO_PATH=/usr/local/demo

Makefile

include .env

demo-path:
    echo ${DEMO_PATH}

Read more

Upvotes: 42

Dyno Fu
Dyno Fu

Reputation: 9044

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

Upvotes: 30

g10guang
g10guang

Reputation: 5285

all:
    echo ${PATH}

Or change PATH just for one command:

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

Upvotes: 29

Related Questions