Matthew Masurka
Matthew Masurka

Reputation: 375

Shell script to check if running in Windows when using WSL?

I'm trying to add a conditional to my .zshrc file that will initialize some config stuff that I only want to happen if I'm in Windows Subsystem for Linux. I tried this but no luck:

if [ "$('cmd.exe /c "systeminfo" | grep "^OS Name"')" =~ "Windows" ]; then
        echo "windows baby!"
fi

Which gives:

no such file or directory: cmd.exe /c "systeminfo" | grep "^OS Name"

...but that command works if I type it directly in the shell. Any ideas?

Upvotes: 3

Views: 2141

Answers (1)

AzuxirenLeadGuy
AzuxirenLeadGuy

Reputation: 2870

Using uname -r does the trick

According to https://github.com/microsoft/WSL/issues/423#issuecomment-608236476, if you use

uname -r | sed -n 's/.*\( *Microsoft *\).*/\1/ip'

You'll get output as "Microsoft" in case it is WSL. Otherwise, you should get no output.

So you can use something like

if [ $(uname -r | sed -n 's/.*\( *Microsoft *\).*/\1/ip') ];
then
        echo "This is Windows WSL baby!"
else
        echo "Not Windows"
fi

Upvotes: 10

Related Questions