如何将环境变量从 WSL 传递到 windows 可执行文件

How do you pass an environment variable from WSL into windows executable

从 Linux (v1) Alpine bash 终端的 Windows 子系统,我想设置一个环境变量,该变量传递给 windows 可执行文件。有什么办法吗?

我希望打印的示例 "Hello, World!":

windows-10:~# export X=World
windows-10:~# cmd.exe /c 'echo Hello, %X%!'
Hello, %X%!

请参阅下面菲利普的回答。

这是来自 https://docs.microsoft.com/en-us/windows/wsl/interop

的相关信息的副本

在 Windows 和 WSL

之间共享环境变量
Available in Windows Insider builds 17063 and later.

在 17063 之前,只有 Windows WSL 可以访问的环境变量是 PATH(因此您可以从 WSL 下启动 Win32 可执行文件)。

从 17063 开始,WSL 和 Windows 共享 WSLENV,这是一个特殊的环境变量,用于在 WSL 上桥接 Windows 和 Linux 发行版 运行。

WSLENV 的属性:

It is shared; it exists in both Windows and WSL environments.
It is a list of environment variables to share between Windows and WSL.
It can format environment variables to work well in Windows and WSL.

WSLENV 中有四个标志可用于影响环境变量的翻译方式。

WSLENV 标志:

/p - translates the path between WSL/Linux style paths and Win32 paths.
/l - indicates the environment variable is a list of paths.
/u - indicates that this environment variable should only be included when running WSL from Win32.
/w - indicates that this environment variable should only be included when running Win32 from WSL.

可以根据需要组合标志。

你能试试这个吗?

~$ export X=World
~$ export WSLENV=X/w
~$ cmd.exe /c 'echo Hello, %X%!'
Hello, World!