52

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

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

Tim
  • 4,790
  • 4
  • 33
  • 41
  • What does 'uname -a' report? – D.Shawley Aug 23 '16 at 01:20
  • `uname -a` output from Ubuntu on Windows: `Linux COMPUTER 3.4.0+ #1 PREEMPT Thu Aug 1 17:06:05 CST 2013 x86_64 x86_64 x86_64 GNU/Linux` – Tim Aug 23 '16 at 01:23
  • 1
    https://github.com/microsoft/WSL/issues/423 answers the question, `/proc/sys/kernel/osrelease` is a string from the kernel, so it doesn't depends on the distro and the most reliable way. – gavenkoa Jul 03 '21 at 21:20

1 Answers1

88

It looks like /proc/version in Ubuntu on Windows contains:

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

and my version of Ubuntu has:

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:

if grep -qi microsoft /proc/version; then
  echo "Ubuntu on Windows"
else
  echo "native Linux"
fi
sorin
  • 161,544
  • 178
  • 535
  • 806
Tim
  • 4,790
  • 4
  • 33
  • 41
  • 7
    [From an official source](https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364): Searching `/proc/version` or `/proc/sys/kernel/osrelease` for the strings `"Microsoft"` or `"WSL"` is the best way to do this. – Tim Aug 09 '16 at 22:07
  • 3
    `if [[ "$(< /proc/sys/kernel/osrelease)" == *Microsoft ]]; then ... else ... fi` is faster since it avoids spawning a `grep` process – Niklas Holm Jan 11 '19 at 07:43
  • 1
    @NiklasHolm You are wrong. `$(...)` spawns process. Use `read var – gavenkoa May 15 '19 at 13:23
  • 1
    @gavenkoa I didn't say it doesn't spawn a process, but it is faster than spawning grep. – Niklas Holm May 21 '19 at 16:28
  • @NiklasHolm There is a trick with `read var` to avoid process spawning, – gavenkoa May 22 '19 at 19:08
  • This one worked on WSL 1. On WSL 2 it's lowercase microsoft. So I just used `if grep -q icrosoft /proc/version; then` – zeykzso Jun 25 '20 at 12:54
  • 5
    Try `grep -qi microsoft /proc/version` to detect the spuriously cased "[M|m]icrosoft" – a505999 Oct 29 '21 at 01:59