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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…