1

In my ~/.bashrc I detect running platform with OSTYPE (it can be cygwin for instance).

How should I detect WSL in Bash? Previously I used COMSPEC env var but it is missing inside WSL...

I prefer lightweight check without spawning external processes which are not cheap in WSL/Cygwin.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
  • 1
    Possible duplicate of [How to check if a program is run in Bash on Ubuntu on Windows and not just plain Ubuntu?](https://stackoverflow.com/questions/38086185/how-to-check-if-a-program-is-run-in-bash-on-ubuntu-on-windows-and-not-just-plain) – pjh Oct 15 '18 at 19:41
  • Also see [Detect “Ubuntu on Windows” vs native Ubuntu from bash script](https://stackoverflow.com/q/38859145/4154375). – pjh Oct 15 '18 at 19:43

2 Answers2

3

You could check /proc/version. On my machine (Win 10 1809), it contains:

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
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
1

uname would also be an option, i.e.

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

This approach will work, as the kernel version string is slightly different under WSL2, than WSL1.

$ uname -r
5.4.72-microsoft-standard-WSL2