从 bash 脚本检测“Windows 上的 Ubuntu”与本机 Ubuntu

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38859145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:01:26  来源:igfitidea点击:

Detect "Ubuntu on Windows" vs native Ubuntu from bash script

bashwindows-subsystem-for-linux

提问by Tim

Can a bash script detect if it's running in "Ubuntu on Windows" vs native Ubuntu? If so, how?

bash 脚本是否可以检测它是在“Windows 上的 Ubuntu”还是本机 Ubuntu 中运行?如果是这样,如何?

I ran envon both machines and didn't see any obvious environmental variable differences. I could test for the existence of the /mnt/cdirectory, but that is not foolproof because that directory could potentially also be present on native Ubuntu.

env在两台机器上运行,并没有看到任何明显的环境变量差异。我可以测试该/mnt/c目录是否存在,但这并不是万无一失的,因为该目录也可能存在于本机 Ubuntu 上。

回答by Tim

It looks like /proc/versionin Ubuntu on Windows contains:

/proc/version在 Windows 上的 Ubuntu 中看起来包含:

Linux version 3.4.0-Microsoft ([email protected]) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Wed Dec 31 14:42:53 PST 2014

Linux version 3.4.0-Microsoft ([email protected]) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Wed Dec 31 14:42:53 PST 2014

and my version of Ubuntu has:

我的 Ubuntu 版本有:

Linux version 4.4.0-31-generic (buildd@lgw01-16) (gcc version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2.1) ) #50-Ubuntu SMP Wed Jul 13 00:07:12 UTC 2016

Linux version 4.4.0-31-generic (buildd@lgw01-16) (gcc version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2.1) ) #50-Ubuntu SMP Wed Jul 13 00:07:12 UTC 2016

This code is working for me to detect which version of Ubuntu the script is running on:

这段代码让我可以检测脚本在哪个版本的 Ubuntu 上运行:

if grep -q Microsoft /proc/version; then
  echo "Ubuntu on Windows"
else
  echo "native Linux"
fi