【问题标题】:Detect "Ubuntu on Windows" vs native Ubuntu from bash script [duplicate]从 bash 脚本检测“Windows 上的 Ubuntu”与本机 Ubuntu [重复]
【发布时间】:2016-12-15 23:54:07
【问题描述】:

bash 脚本能否检测它是在“Windows 上的 Ubuntu”还是在本机 Ubuntu 中运行?如果有,怎么做?

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

【问题讨论】:

  • 'uname -a' 报告什么?
  • uname -a Windows 上 Ubuntu 的输出:Linux COMPUTER 3.4.0+ #1 PREEMPT Thu Aug 1 17:06:05 CST 2013 x86_64 x86_64 x86_64 GNU/Linux
  • github.com/microsoft/WSL/issues/423 回答了这个问题,/proc/sys/kernel/osrelease 是来自内核的字符串,所以它不依赖于发行版和最可靠的方式。

标签: bash windows-subsystem-for-linux


【解决方案1】:

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

Linux version 3.4.0-Microsoft (Microsoft@Microsoft.com) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Wed Dec 31 14:42:53 PST 2014

我的 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

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

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

【讨论】:

  • From an official source:搜索/proc/version/proc/sys/kernel/osrelease 中的字符串"Microsoft""WSL" 是最好的方法。
  • if [[ "$(< /proc/sys/kernel/osrelease)" == *Microsoft ]]; then ... else ... fi 更快,因为它避免产生grep 进程
  • @NiklasHolm 你错了。 $(...) 产生进程。使用read var </proc/sys/kernel/osrelease,然后检查var 值。
  • @gavenkoa 我没有说它不会产生进程,但它比产生 grep 更快。
  • 尝试grep -qi microsoft /proc/version 检测虚假大小写的“[M|m]icrosoft”
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 2017-07-11
  • 2012-01-28
  • 2021-09-05
  • 1970-01-01
  • 2016-10-14
  • 2016-07-08
相关资源
最近更新 更多