Yes it is exactly what you think.

Challenge

Create a program that returns a truthy value when run on Microsoft Windows (for simplicity we'll stick with Windows 7, 8.1 and 10) and a falsey value when run on any other operating system (OSX, FreeBSD, Linux).

Rules

  • Code that fails to run/compile on a platform doesn't count as a falsey value.

Winning criteria

I'm labelling this as , so lowest score wins, but I'm also very interested in seeing creative solutions to this problem.

share|improve this question
5  
Can the programs output by exit code? (normally allowed) – FlipTack yesterday
    
I'm gonna say yes @FlipTack – Daniel yesterday
7  
Can you give a definite list of which operating systems this needs to work on? – FlipTack yesterday
1  
What should the result be under Windows RT? – Adám yesterday
1  

35 Answers 35

MATLAB, 4 bytes

ispc

From the documentation:

tf = ispc returns logical 1 (true) if the version of MATLAB® software is for the Microsoft® Windows® platform. Otherwise, it returns logical 0 (false).

There are also the functions ismac and isunix. I'll leave it to the reader to figure out what those functions do. Mego kindly asked for diagrams explaining ismac and isunix so I've tried to illustrate it here:

enter image description here

It was not asked for a diagram of ispc but I can reveal that the behaviour is pretty similar, except substitute OSX and Unix with Windows.


Second approach:

If someone is not satisfied with this answer, I'll provide a second approach with getenv using 19 bytes that should be bullet proof, unless there's another operating system starting with W:

getenv('OS')(1)==87

getenv 'name' searches the underlying operating system environment list for text of the form name=value, where name is the input character vector. If found, MATLAB® returns the character vector value. If the specified name cannot be found, an empty matrix is returned.

share|improve this answer
6  
@z0rberg's It does, though. ispc is truthy iff the Matlab installation is for MS Windows. Though it could be run on WINE and still be truthy - I'd consider that "running on MS Windows", since WINE is a Windows compatibility layer. The same thing goes for WSL in Windows 10 - you're actually running Linux (in/with Windows), so it should be false. – Mego yesterday
2  
@z0rberg's Because you cannot install the Windows version on anything but Windows (WINE counts as Windows here). It is a Windows installer, and installs Windows executables. The only way ispc will be true is if it was installed on a Windows platform - you couldn't even run the installer otherwise. – Mego yesterday
1  
My conclusion: This post cheats, because WINE Is Not an Emulator... but i guess i can't change that. Thank you for your time! – z0rberg's yesterday
3  
@z0rberg's But this makes no sense. As I said, most of the answers here will detect wine as being Windows. Wine "emulates" backslashes. Wine "emulates" a C drive and a Windows directory. Wine reproduces ALL these things. Running ANY of these answers under Wine, or at least the vast majority of them, will say that they're running under Windows. – Muzer 20 hours ago
4  
@z0rberg's how about instead of trolling this particular answer, you ask the OP for clarification on the rules? As other people have noted, WINE is specifically designed to appear to the hosted programs to BE Windows for all practical purposes, so it's not very surprising or problematic that many answers (not just this one) would recognize WINE as Windows. – Blackhawk 13 hours ago

Python 2.7.10, 24 bytes

import os
0/('['>os.sep)

Thanks to FlipTack for 3 bytes

This program takes advantage of the fact that Windows is the only OS to use \ as a path separator. Normally this is frustrating and bad, but for once it is actually an advantage. On Windows, '['>os.sep is false, and thus 0/0 is computed, causing a ZeroDivisionError and exiting with a non-zero exit code. On non-Windows platforms, '['>os.sep is true, making the expression 0/1, which does nothing, and the program exits with exit code 0.

share|improve this answer
    
DOS also uses a backslash as the path separator and it has at least one Python 2 implementation. – isanae yesterday
2  
@isanae I've edited the title to specify Python 2.7 - the only Python 2 implementation on DOS is an archaic, buggy 2.4.2 – Mego yesterday
    
OS/2 also uses a backslash and has a Python 2.7 implementation ;) – isanae yesterday
2  
@isanae There, I specified 2.7.10. Good luck finding a port of that. – Mego yesterday
1  
apparently it only needs to give correct results on 3 recent windows versions and presumably similarly recent versios of the three other systems listed, OS2 and DOS don't matter, – Jasen yesterday

PHP, 22 bytes

`<?=PATH_SEPARATOR>":";`  

prints 1 if the path separator is semicolon (colon or empty for all other OSs except for DOS and OS/2), else nothing.

also 22 bytes, but not that safe:

<?=strpos(__FILE__,92);

prints a positive integer if the file path contains a backslash; else nothing.
A safe alternative with 27 bytes: <?=DIRECTORY_SEPARATOR>"/"; prints 1 or nothing.

Strange: <?=__FILE__[1]==":"; (20 bytes) should be, not safe either, but ok. But although __FILE__ pretends to be a string (I tried var_dump and gettype), indexing it throws an error (at least in online testers).
I´ll try it on my server tomorrow. Will someone test it on Windows?

27 bytes: <?=stripos(PHP_OS,win)===0;
tests if predefined PHP_OS constant starts with win (case insensitive; Windows,WIN32,WINNT, but not CYGWIN or Darwin); prints 1 for Windows, else nothing.

17/18 bytes:

<?=strlen("
")-1;

prints 1 if it was stored with Windows linebreak (also on DOS, OS/2 and Atari TOS - although I doubt that anyone ever compiled PHP for TOS), else 0.

You could also check the constant PHP_EOL.

more options:

PHP_SHLIB_SUFFIX is dll on Windows, but not necessarily only there.
php_uname() returns info on the operating system and more; starts with Windows for Windows.
$_SERVER['HTTP_USER_AGENT'] will contain Windows when called in a browser on Windows.
<?=defined(PHP_WINDOWS_VERSION_BUILD); (38 bytes) works in PHP>=5.3

conclusion

The only failsafe way to tell if it´s really Windows, not anything looking like it, seems to be a check on the OS name. For PHP: php_os() may be disabled for security reasons; but PHP_OS will probably always contain the desired info.

share|improve this answer
4  
File names on *nix can contain backslashes, so this isn't really foolproof. The rules don't say it has to be foolproof, though, so ¯\_(ツ)_/¯ – Jordan yesterday
    
@Jordan: You´re right. I added that info to the description. Thanks. – Titus yesterday
4  
An alternative: <?=class_exists(COM);. The class COM is only available under Windows, as far as I know. That should save you one byte. – Ismael Miguel yesterday
    
@IsmaelMiguel That's enough of a different answer for you to post it as such. (However, it may not be worth it to do so; this answer is very well written.) – wizzwizz4 17 hours ago
1  
@wizzwizz4 It isn't worth it. The answer would be pushed to oblivion. That's why I simply left the comment, instead of writting my own answer. – Ismael Miguel 17 hours ago

Vim, 2 bytes

<C-a>1

On Windows, <C-a> (ctrl+a) is mapped by default to Select All. If you type a 1 in select mode in Windows, it replaces the selection with what you typed (1) leaving a 1 in the buffer.

On other operating systems, <C-a> by default is mapped to Increment number. Because there's no number to increment, it's a no-op, and then the 1 increases the count but in terms of the buffer is a no-op.

1 is truthy in Vim, and an empty string is falsy

share|improve this answer
    
Looks like 3 keystrokes. Ctrl+a+1 – Pavel yesterday
6  
I think per this meta post meta.codegolf.stackexchange.com/questions/8995/… Vim answers are generally scored without the modifiers (especially given that the first answer on the post uses <ctrl+a> as an example for 1 byte) – nmjcman101 yesterday
    
@Pavel it's Ctrl + a, 1. If it were Ctrl + a + 1 it'd be counted as 1 keystroke. – Captain Man 14 hours ago
    
Beautiful, I love this answer! – DJMcMayhem 4 hours ago

C, 44 43 38 36 bytes

Thanks to @Downgoat for a byte! crossed out 44 is still regular 44
Thanks to @Neil for two bytes!

f(){return
#ifdef WIN32
!
#endif
0;}
share|improve this answer
    
Originally I was going to suggest that you can save a bunch of bytes by moving the 0 out of the ifdef and changing the 1 to !, but I think _WIN32+0 works even better still. – Neil yesterday
    
If c99 is OK you can change f to main and stick return 1; inside the ifdef and remove the else, since main without return in c99 must return 0. – gurka yesterday
5  
That's a compiler directive. If it's compiled on a Windows system and run on a Linux system, for example, it will still return 1. – Micheal Johnson yesterday
    
Do you need _ in WIN32? I never added it on my code – Downgoat yesterday
3  
@MichealJohnson no. I can compile it on linux (using mingw32gcc msvc) snd get code that returns true when run on windows. I don't know of any windows-hosted linux compiler. if you want to argue emulation layers like "wine" all the other answers probably suffer the same problem – Jasen yesterday

x86 Assembly, 3 bytes (Inspired by Runemoro's answer)

40 CD 80

Or

inc eax
int 0x80

Description

First of all, we'll set eax to 1 (the system call number for exit(int val) for Linux, FreeBSD and OSX). Then, we'll call the interrupt gate 0x80 which is the system call gate for Linux, FreeBSD and OSX. That would cause the program to exit with status of ebx which is 0 (false).

On Windows int 0x80 is an invalid gate (It uses 2e as a syscall gate) and would crash the program, causing it to end with a positive exit code (true).

References and further reading

share|improve this answer
2  
That's brilliant! – z0rberg's 18 hours ago
    
Why does the crash cases a truthy value? Is it because EAX (typically the return value) is 1? Also, is EAX guaranteed to be 0 at program start? Or do you need xor eax, eax in there? – Cole Johnson 13 hours ago
    
@ColeJohnson: OS-detected crashes (on the operating systems typically used with x86) never leave an exit code of 0, because that's reserved for successful termination. (Normally the exit code is some wonky value that the OS reserves specifically for this circumstance.) However, I'm not sure it makes sense to count 0 as falsey and 1 as truthy in program exit codes, given that the normal convention is the exact opposite (with 0 being the only truthy vaue, e.g. the standard UNIX/Linux/POSIX program false exits with code 1 whilst true exits with code 0). – ais523 5 hours ago

Mathematica, 28 bytes

$OperatingSystem=="Windows"&
share|improve this answer
    
What's the point in making it a function? You could remove the ampersand saving one byte, and the code would just directly evaluate whether it's executed is on a Windows-ish system. – Ruslan yesterday
    
@Ruslan All answers must be either full programs that print the result or callable functions. If this is declared a Mathematica notebook answer, then you might get away with calling it a full program, but if I invoke the thing from the command-line without the &, it won't print anything (and it's then also not a callable function, but merely a snippet/expression). – Martin Ender yesterday
    
@MartinEnder Really no output? I get Out[1]= False output from this: ~/opt/Mathematica/11.0/Executables/math <<< '$OperatingSystem=="Windows"' – Ruslan yesterday
    
@Ruslan I believe that also starts a notebook environment (just a command-line based one). What I mean by running a program from the command-line is using script mode. – Martin Ender yesterday

Java 8, 33 bytes

Special thanks to Olivier Grégoire for suggesting separatorChar, and Kritixi Lithos for -1 byte!

This is a lambda expression which returns a boolean. This can be assigned to Supplier<Boolean> f = ...; and called with f.get().

()->java.io.File.separatorChar>90

Try it online! - the server isn't windows, so this prints false. However, in my windows machine, the same code prints true.

What this code does is get the System's file seperator, and check whether its codepoint is larger than the character [. This true for Windows, as it uses \ as the seperator - but every other OS uses /, which has a lower code in the ASCII table.

share|improve this answer
    
Won't this break on other OSes which start with W? – Downgoat yesterday
    
()->java.io.File.separatorChar=='\\' is only 36 bytes. – Olivier Grégoire yesterday
1  
@OlivierGrégoire nice one - and I can golf it to 34 using ()->java.io.File.separatorChar>'['! – FlipTack yesterday
1  
@Titus WebOS, Whonix. Probably even more. – Olivier Grégoire yesterday
1  
@Titus Wait, what about WAITS? – SeeOneRhino 18 hours ago

J, 7 bytes

6=9!:12

This is a verb (similar to a function) that uses the builtin foreign conjunction 9!:12 to acquire the system type where 5 is Unix and 6 is Windows32.

share|improve this answer

Befunge-98, 7 bytes

6y2%!.@

Try it online!

This works by querying the system path separator, which is \ on Windows and / on other operating systems.

6y            System information query: #6 returns the path separator.
  2%          Test the low bit - this will be 1 for '/' and 0 for '\'.
    !         Not the value, so it becomes 0 for '/' and 1 for '\'.   
     .@       Output the result and exit.
share|improve this answer

julia, 10 bytes

is_windows

A function that returns true for windows

share|improve this answer

x86 machine code, 9 bytes

40 39 04 24 75 02 CD 80 C3

Compiled from:

inc eax        ; set eax to 1
cmp [esp], eax ; check if [esp] == 1 (linux)
jne windows    ; jump over "int 0x80" if on windows
int 0x80       ; exit with exit code 0 (ebx)
windows:
ret            ; exit with exit code 1 (eax)
share|improve this answer
3  
pure binary (COM) won't run on Windows or Linux so not sure if this is valid – Igor Skochinsky yesterday
    
@IgorSkochinsky There must be an interpreter for assembly. – Shmuel H. 20 hours ago
    
You can make the code even shorter by leaving only inc eax and int 0x80, I think it should fail on windows and terminate the process. – Shmuel H. 20 hours ago
    
@ShmuelH. We aren't allowed to do that: "Code that fails to run/compile on a platform doesn't count as a falsey value." – Runemoro 20 hours ago
2  
@IgorSkochinsky There are programs that run raw binary too. See the link in my previous comment. – Shmuel H. 20 hours ago

Batch, 50 bytes

@if %OS%==Windows_NT if not exist Z:\bin\sh echo 1

Edit: Fixed to ignore DOS instead of claiming that it's Windows.

The only other way I know of running Batch outside of Windows is to use WINE which by default will map Z: to /. Therefore if Z:\bin\sh exists, chances are that it's /bin/sh, so not MS Windows.

I don't know what WINE sets %OS% to, but if it's not Windows_NT then I could save 23 bytes.

share|improve this answer
1  
Another way is DOS, which is not Windows. – Ruslan yesterday
    
Not only does this fail under DOS, but also, on a computer where Z: is mapped, and happens to contain such a path. – Adám yesterday
    
This doesn't work if cygwin is install to the root of drive Z: – DavidPostill yesterday
3  
@Adám Sure and if you compile the C answer with -DWIN32=1 then it fails too. Your point? – Neil yesterday
1  
yes, wine sets OS=Windows_NT – Jasen yesterday

R, 15 bytes

.Platform$O>"v"

Thanks to plannapus for the suggestion to use partial matching for list element extraction.

.Platform is a list with some details of the platform under which R was built. There is an element OS.type (the only element with name starting with "O") which is character string, giving the Operating System (family) of the computer. One of "unix" or "windows".

So "unix" is less then "v", but "windows" is greater then "v". Other valid 15 bytes answers are

.Platform$O>"V"
.Platform$O>"w"
.Platform$O>"W"

R is being developed for the Unix-like, Windows and Mac families of operating systems. Other OS families are not supported.

share|improve this answer
1  
there are platforms other than unix that aren't windows you know... – muddyfish yesterday
1  
@muddyfish: .Platform[[1]] is defined as either "unix" or "windows" in R documentation. github.com/wch/r-source/blob/… – liori yesterday
    
Sorry, that's ok then. The answer should probably be modified to include this fact to stop that being asked again – muddyfish yesterday
2  
You can use partial matching of list elements for a shorter code (as OS.type is the only element starting with O): .Platform$O!="unix" – plannapus yesterday

Perl 6,  19  18 bytes

put $*DISTRO.is-win
put ?($*CWD~~/\\/)

Both output True␤ or False␤ depending on the system it is run on.

share|improve this answer
    
the second one relies on the non windows values of CWD not containing any `` - there's no guarantee of that, – Jasen yesterday

Dyalog APL, 21 bytes

'W'=⊃⊃⎕WG'APLVersion'

⎕WG'APLVersion' system function Windows Get property APL Version

pick the first element (Target Environment)

pick the first letter (Windows/Linux/AIX/Solaris)

'W'= W equal to that letter?

share|improve this answer

C#, 61 bytes

bool f(){return(int)System.Environment.OSVersion.Platform<4;}

Or a full program at 83 bytes:

class P{static int Main(){return(int)System.Environment.OSVersion.Platform<4?1:0;}}

Various Windows variants use enum values 0 to 3 in the Microsoft .NET implementation. 4 is Unix, 5 is Xbox (which I won't consider "Windows"), 6 is MacOSX. Mono uses the same values, adding 128 for Unix/Linux in earlier versions.

Therefore, anything < 4 is Windows, and everything else is not Windows.

share|improve this answer

QBasic, 31 bytes

?INSTR(ENVIRON$("COMSPEC"),"W")

Prints non-zero under Windows, 0 under everything else.

COMSPEC is an environment variable unique to Microsoft OSs. It points to the command interpreter, typically command.com or cmd.exe. Under Windows, the command interpreter sits somewhere in the Windows directory; under MS-DOS, it sits in the DOS directory or on the root of the disk, and under any other OS, it doesn't exist.

By checking to see if the value of COMSPEC contains a "W", we can tell the difference between Windows and not-Windows.

share|improve this answer
    
COMSPEC isn't reserved to mean anything in particular under Linux (meaning it's under user control by default), so isn't it possible that the user's set it to a value that they're using for their own purposes (and happens to contain a W)? Admittedly, that's a bit of an edge case. – ais523 5 hours ago
    
@ais523: Also, the Windows directory doesn't have to contain a W. It's brittle in either case. – Joey 3 hours ago

JavaScript, 42 30 26 bytes

console.log((
//Begin
_=>navigator.oscpu[0]=='W'
//End
)())

Only Windows has an oscpu value starting with W, according to this post. Also, tested with Firefox. Chrome doesn't have the oscpu property.

Edits

  1. Saved 12 bytes thanks to Neil.
  2. Saved another four bytes
share|improve this answer
    
oscpu is probably the shortest navigator property that you can use. Also, testing a regexp will probably work out shorter, but I haven't measured it. – Neil yesterday
    
You can remove !=-1 and add a ~ right after the fat arrow, saving 3 bytes. – L. Serné yesterday
    
Do you have to create a function? Can't you just console.log the regex test? Also would navigator.oscpu[0]=='W' work or is there another OS that also starts with W. – Masterzagh yesterday
2  
Hmm, for some reason my Chrome doesn't have oscpu. – Muzer 22 hours ago
    
If it wasn't for WebTV OS, I would suggest navigator.platform[0]=='W' as a more robust alternative. – Patrick Roberts 1 hour ago

Excel VBA, 41 40 Bytes

Immediate windows function that returns if the true if the name of the operating system starts with W. This will only ever be true on Windows based systems as Excel VBA is restricted to Windows and OSX.

?Left(Application.OperatingSystem,1)="W"

-1 Thanks to Neil for using Left(...,1) over Mid(...,1,1)

share|improve this answer
1  
left saves you a byte. – Neil yesterday
    
Have you tried it on office365 online? Does that even support VBA? Just curious. – Chris H 31 mins ago

Node.js, 27 bytes

_=>require('path').sep!='/'
share|improve this answer
    
If you change this to Node.js REPL, you can save 16 bytes by just using _=>path.sep!='/' – Patrick Roberts 2 hours ago
    
I'm new to codegolf. Am I allowed to do that? – GilZ 2 hours ago
    
Yes, otherwise I wouldn't have suggested it. REPL means read, execute, print loop, the program that runs when you enter node on the console. From there, all the system node modules are available without the need to require() them. – Patrick Roberts 2 hours ago

PHP 17 Bytes

The following will output 1 if windows and nothing if anything else. Ignoring notices of string convertion.

<?=PHP_OS==WINNT;

Try online Online tests for linux because the sandbox is linux for PoC.

share|improve this answer
    
Sure that is enough? Asking because Possible Values For: PHP_OS. – manatwork yesterday
    
'<?=PHP_OS[0]==W;` is both 1 byte shorter and catches all the other windows values in the question linked by manatwork. >V might work too. – user59178 yesterday

Perl, 12 bytes

print$^O=~/W/

^O should be replaced by a literal Control-O.

Outputs 1 on windows, nothing on another OS.

Note that I'm not using say as it adds a trailing newline, which is truthy in Perl.

-1 bytes thanks to ais523.

share|improve this answer
    
AFAIR this won't work in Cygwin Perl. – Igor Skochinsky yesterday
    
This won't work in mingw Perl either. Perl treats those both as distinct operating systems from Windows, though (as they generally obey UNIX rather than Windows conventions), and it's not clear whether they should count for the purpose of the question. In other news, you can save a byte here by using a literal control-O character rather than ^O. – ais523 5 hours ago
    
@ais523 I edited that, thanks. As for Cygwin and Mingw, I'll delete the post if they should be considered as Windows, but as you say, it would make more sense to consider them like separate OS (or at least, like not-Windows OS). – Dada 5 hours ago

tcl, 38 bytes

 expr [lsearch $tcl_platform windows]>0
share|improve this answer

Java 8, 49 bytes

()->System.getenv().get("OS").contains("Windows")

Longer than the other Java answer, but takes a different approach.

This lambda fits in a Supplier<Boolean> and can be tested with the following program:

public class DetectMSWindows {

  public static void main(String[] args) {
    System.out.println(f(() -> System.getenv().get("OS").contains("Windows")));
  }

  private static boolean f(java.util.function.Supplier<Boolean> s) {
    return s.get();
  }

}
share|improve this answer
    
It's very, very similar to the initial answer that you link (before the edits). – Olivier Grégoire yesterday

8th, 11 characters

 
os 1- not .
 

Prints true on Windows, false on Linux and macOS. Other platforms supported by 8th are Android, iOS and Raspberry Pi, but I am not able to test on them.

Ungolfed version (with comments)

 
G:os  \ Return a number n indicating the operating system 
      \ 0 for Linux
      \ 1 for Windows 
      \ 2 for macOS
      \ 3 for Android 
      \ 4 for iOS 
      \ 5 for Raspberry Pi
n:1-  \ Subtract 1
G:not \ If Windows --> true, otherwise --> false
.     \ Print result
 
share|improve this answer

FPC, 61 chars

begin{$ifdef win32}write('f');{$else}write('nf');{$endif}end;
share|improve this answer
    
you can shave some bytes by using only one write begin write({$ifdef win32}1{$else}0{$endif});end. – hdrz yesterday
    
Or to work on win64 as well: begin write({$ifdef windows}1{$else}0{$endif})end. – hdrz yesterday
    
@hdrz, yes, you right, thanks ;) – monobogdan1 yesterday
    
@hdrz, sure that would be correct? 1 and 0 are not truthy/falsey in Pascal. I would go with begin write(1={$ifdef windows}1{$endif}+0)end. – manatwork yesterday
    
@manatwork, FPC and Delphi supports various types in writeln. And boolean is can be only 0 or 1 in pascal – monobogdan1 yesterday

Haskell, 39 31 bytes

import System.Info
f=os!!0=='m'

I check for the first letter output of "m", which should be "mingw" for windows. As far as I could tell, there is no other OS which starts with M. The information comes from https://github.com/ghc/ghc/blob/master/compiler/utils/Platform.hs

share|improve this answer
1  
On my system (Windows 10 64-bit, GHC 8.0.1 64-bit), os gives "mingw32". – Mego yesterday
    
@Mego you are right, corrected for that – Dylan Meeus yesterday

tcl, 51

puts [string match windows $tcl_platform(platform)]

I don't have a Windows machine online, but on http://rextester.com/live/OVTY1488 replace windows by unix to see it output 1 instead of 0.

2nd attempt:

tcl, 40

puts [string match W* $tcl_platform(os)]

assuming Windows is the only system the name begins on a W.

3rd attempt:

tcl, 26

puts [info exists env(OS)]

assuming Windows is the only system the OS environment variable is defined.

share|improve this answer

Racket, 26 17 bytes

Shameless plug for the TCL answer I saw that used the OS environment variable.

(and(getenv"OS"))

(Old answer)

Pretty straight forward. system-type with no argument returns a symbol indicating the system operating system type.

(eq?'windows(system-type))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.