Is my output going to bash.exe or cmd.exe?

If you want to color the output of your terminal program in Windows, you might've noticed, that running it from different shells reacts differently.

cmd.exe does not recognize the ANSI escape sequences to change the foreground/background color, while bash.exe does not recognize Windows' SetConsoleTextAttribute. This poses a problem. A way to detect if the output is going to bash.exe or cmd.exe is required.

Fortunately, an old mail on the Cygwin mailing list1 hinted to the fact that GetFileType for the console handle returned by GetStdHandle is different. And after a little testing, it in fact is! Equipped with this information, we can now distinguish between our output terminals:

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  
DWORD dwFiletype = GetFileType(hConsole);  
if (dwFiletype == 0x3) {  
    /* We're running in bash.exe */
} else if (dwFiletype == 0x2) {
    /* We're running in cmd.exe */
}

Questions? Criticism? Wanna talk? I'm @ArvidGerstmann on Twitter.

  1. Despite the author saying it's a bug, this isn't the case, as later emails in the thread confirm.