如何将 WSL 中的环境变量传递到 Windows 可执行文件中

Joh*_*ann 4 bash environment-variables windows-subsystem-for-linux

从 Linux (v1) Alpine bash 终端的 Windows 子系统中,我想设置一个环境变量,该变量被传递到 Windows 可执行文件中。有没有办法做到这一点?

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

windows-10:~# export X=World
windows-10:~# cmd.exe /c 'echo Hello, %X%!'
Hello, %X%!
Run Code Online (Sandbox Code Playgroud)

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

这是来自https://docs.microsoft.com/en-us/windows/wsl/interop的相关信息的副本

在 Windows 和 WSL 之间共享环境变量

Available in Windows Insider builds 17063 and later.
Run Code Online (Sandbox Code Playgroud)

在 17063 之前,只有 WSL 可以访问的 Windows 环境变量是 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.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

可以根据需要组合标志。

Phi*_*ppe 5

你能试试这个吗?

~$ export X=World
~$ export WSLENV=X/w
~$ cmd.exe /c 'echo Hello, %X%!'
Hello, World!
Run Code Online (Sandbox Code Playgroud)

  • @user1934428 根据[这篇关于“WSLENV”的文章](https://devblogs.microsoft.com/commandline/share-environment-vars- Between-wsl-and-windows/),“/w”意味着 var 只会在 WSL 中从 bash 执行 Windows 进程时存在:“仅当从 WSL 调用 Win32 时才应包含该值” (2认同)