Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Pretty straightforward, the usual places to figure out the OS you're on seem to be identical to plain Ubuntu on Ubuntu for Windows. For example uname -a is identical to a native GNU/Linux install and /etc/os-version is identical to a Ubuntu Trusty Tahr install.

The only thing I can think of is to check if /mnt/c/Windows exists, but I'm not sure if that's a foolproof idea.

like image 335
DrKabob Avatar asked Jun 28 '16 20:06

DrKabob


People also ask

How do I check if a program is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do I know if Windows is bash?

Press Windows key + X then click Command prompt, at the command prompt, type: bash then hit Enter. If you want to be able to access the local file system, press Windows key + X, Command Prompt (Admin) then type bash at the prompt.

Is bash for Windows or Linux?

Note that bash runs natively on Windows 10, which is different from using emulators like 'cygwin' for Windows which enabled GNU tools to run on unsupported Windows environment. Also, Linux subsystem for Windows 10 is only available on the 64-bit version of the OS.

Is bash and Ubuntu the same?

Bash is a popular text-based shell and command-language. It is the default shell included within Ubuntu and other Linux distros, and in macOS.


2 Answers

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

#!/bin/bash set -e if 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't promise that we'll never change the content of these ProcFs files, but I think it's unlikely we'll change it to something that doesn't contain "Microsoft" or "WSL".

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

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

like image 52
Gary S. Weaver Avatar answered Oct 07 '22 20:10

Gary S. Weaver


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).

like image 27
Shital Shah Avatar answered Oct 07 '22 19:10

Shital Shah