Bash检测WSL

Bash detect WSL

在我的 ~/.bashrc 中,我用 OSTYPE 检测到 运行 平台(例如可以是 cygwin)。

我应该如何在 Bash 中检测 WSL?以前我使用 COMSPEC env var 但它在 WSL 中丢失...

我更喜欢不产生外部进程的轻量级检查,这在 WSL/Cygwin 中并不便宜。

您可以查看 /proc/version。在我的机器上(Win 10 1809),它包含:

Linux version 4.4.0-17763-Microsoft (Microsoft@Microsoft.com) (gcc version 5.4.0 (GCC) ) #55-Microsoft Sat Oct 06 18:05:00 PST 2018

uname 也是一个选项,即

if [[ $(uname -r) =~ WSL ]]; then
    # WSL detected
    <run code>
fi

此方法可行,因为内核版本字符串在 WSL2 下与 WSL1 略有不同。

$ uname -r
5.4.72-microsoft-standard-WSL2