Shell 使用 WSL 时检查 Windows 中是否有 运行 的脚本?

Shell script to check if running in Windows when using WSL?

我正在尝试向我的 .zshrc 文件添加一个条件,它将初始化一些我只想在 Windows Linux 子系统中发生的配置内容。我试过了,但没有成功:

if [ "$('cmd.exe /c "systeminfo" | grep "^OS Name"')" =~ "Windows" ]; then
        echo "windows baby!"
fi

给出:

no such file or directory: cmd.exe /c "systeminfo" | grep "^OS Name"

...但是如果我直接在 shell 中键入该命令,该命令将起作用。 有什么想法吗?

使用 uname -r 就可以了

根据https://github.com/microsoft/WSL/issues/423#issuecomment-608236476,如果您使用

uname -r | sed -n 's/.*\( *Microsoft *\).*//ip'

如果是 WSL,您将得到 "Microsoft" 的输出。否则,你应该没有输出。

所以你可以使用像

这样的东西
if [ $(uname -r | sed -n 's/.*\( *Microsoft *\).*//ip') ];
then
        echo "This is Windows WSL baby!"
else
        echo "Not Windows"
fi