Home > Software engineering >  load environment variables from a file in a makefile on windows
load environment variables from a file in a makefile on windows

Time:07-02

So I wanted to create a make run command so that I can test locally. It loads some env vars before running it.

I have a win.env file

set ENV1=val1
set ENV2=val2

and a lin.env file

export ENV1=val1
export ENV2=val2

in the Makefile I have:

run:
ifeq ($(OS),Windows_NT)
    . ./win.env && go run .
else
    . ./lin.env && go run .
endif

On linux it works, but on windows it says:

'.' is not recognized as an internal or external command,
operable probram or batch file.
make: *** [run] Error 1

How can I load the env vars before running my program?

CodePudding user response:

The . command is a feature of the POSIX shell. You are not using a POSIX shell on Windows, you're using Windows cmd.exe.

First, you can't name the file win.env. Windows cares a lot about file extensions so you'll have to name this file win.bat or something like that.

Second, in Windows cmd.exe you just run the script; it doesn't start a new command program like POSIX systems do.

run:
ifeq ($(OS),Windows_NT)
        win.bat; go run .
else
        . ./lin.env && go run .
endif
  • Related