Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...