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

后端 未结 10 620
时光说笑
时光说笑 2020-12-05 02:07

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 ide

相关标签:
10条回答
  • 2020-12-05 02:53

    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.

    0 讨论(0)
  • Windows Subsystem for Linux 2 (WSL 2) in Windows 10 Pro Insider Preview Build 18917

    /proc/version contains:

    Linux version 4.19.43-microsoft-standard (oe-user@oe-host) (gcc version 7.3.0 (GCC)) #1 SMP...

    0 讨论(0)
  • 2020-12-05 02:57

    I just came up with this for my .bashrc for adding some WSL items to $PATH.

    Works in 1703. Not sure if earlier versions.

    if [[ $(uname -r) =~ Microsoft$ ]]; then
        foo
    fi
    
    0 讨论(0)
  • 2020-12-05 02:57

    If you in Bash and want to avoid fork:

    is_wsl=0
    read os </proc/sys/kernel/osrelease || :
    if [[ "$os" == *Microsoft ]]; then
      is_wsl=1
    fi
    
    0 讨论(0)
提交回复
热议问题