Old question that got bumped today with a new answer, but there's a supported feature for doing this (wslenv
) that hasn't been mentioned.
The OP mentions that they have Windows Subsystem for Linux, but they want to have the .env
files that they use in WSL available in the Windows environment.
Assuming the variable names are static, this is fairly straightforward (no script/parsing necessary):
Take, for example, an .env
with:
export VARIABLE1=foo
export VARIABLE2=bar
export VARIABLE3=baz
Start in WSL/Bash:
cd /mnt/c/
source /path/to/.env
# Substitute powershell.exe for older version
WSLENV=$WSLENV:VARIABLE1:VARIABLE2:VARIABLE3 pwsh.exe
You will then be in a PowerShell instance where the environment is set with the desired variables from your WSL .env
file.
Executing any Windows process from there, such as code
, will propagate the environment to that subprocess.
So, run code
, then open a new terminal inside VSCode.
echo $env:VARIABLE1
... will correctly respond with foo
.
Alternative if the variable names are dynamic
Or convenience method for collecting the variable names
If you want to just generate a list of the variables from your .env
file, something like the following will work:
In WSL/Bash:
source ./.env
for v in $(sed -E 's/export *([^=]*).*/\1/' ./.env); do export WSLENV=$WSLENV:$v; done
# Substitute powershell.exe for older version
pwsh.exe
That will process the .env
file to look for the variable names that need to be added to the $WSLENV
variable.
.env
is loaded exactly. Go doesn't handle.env
natively, you're probably using godotenv. It sets the env variables for the current process (if using it as a library) and might work on windows. If you're sourcing the.env
before running the go program, then that's even more detached and has nothing to do with Go. – Reinoldsource foo.env
, which loads the environment variables within the file. This isn't necessarily specific to Go, it's just that I am having to use this method with a Go app. – Lewellen