How to check if a program is run in Bash on Ubuntu on Windows and not just plain Ubuntu? How to check if a program is run in Bash on Ubuntu on Windows and not just plain Ubuntu? windows windows

How to check if a program is run in Bash on Ubuntu on Windows and not just plain Ubuntu?


The following works in bash on Windows 10, macOS, and Linux:

#!/bin/bashset -eif grep -qEi "(Microsoft|WSL)" /proc/version &> /dev/null ; then    echo "Windows 10 Bash"else    echo "Anything else"fi

You need to check for both "Microsoft" and "WSL" per this comment by Ben Hillis, WSL Developer:

For the time being this is probably the best way to do it. I can'tpromise that we'll never change the content of these ProcFs files, butI think it's unlikely we'll change it to something that doesn'tcontain "Microsoft" or "WSL".

/proc/sys/kernel/osrelease/proc/version

And case shall be ignored for grep. In WSL2, /proc/version gives lowercased microsoft.


Updating answer by @per-lundberg:

if [[ -n "$IS_WSL" || -n "$WSL_DISTRO_NAME" ]]; then    echo "This is WSL"else    echo "This is not WSL"fi

Note: IS_WSL existed in older versions (using lxrun) while WSL_DISTRO_NAME exists in current versions (from Microsoft Store).


I've been looking for ways to detect that as well. So far I've found 2.

  • /proc/sys/kernel/osrelease is "3.4.0-Microsoft"

  • /proc/version is "Linux version 3.4.0-Microsoft(Microsoft@Microsoft.com) (gcc version 4.7 (GCC) ) #1 SMP PREEMPTWed Dec 31 14:42:53 PST 2014"

If you just use the Ubuntu distribution installed by default there should be no problems with using them, as they said that it would be unlikely for them to set either to something that doesn't contain "Microsoft" or "WSL".

However, if you were to install a different Linux distribution, I'm pretty sure that the contents of /proc/sys/kernel/osrelease and /proc/version will change, since the distro wouldn't have been compiled by Microsoft.