Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text output color on windows for stderr

I recently found a post that gave a solution to have the text output by stderr a different color for Linux (bash)

They created the following bash script script

#!/bin/bash
{ $* 2>&1>&3|sed 's,.*,\x1B[33m&\x1B[0m,'>&2;} 3>&1

this causes the output to print yellow text when it is from stderr. stdout still prints the same color.

the script was saved in a directory on $PATH called color. This allows me to run the script with make or scons and it will hi-lite all of the text from stderr in yellow. (could make the text red by changing 33m to 31m)

color make CPU=x64 

This is quite useful for finding errors when compiling.

Is there a similar script that could be used for Windows cmd shell?

Note: I have sed installed on my windows computer if that is helpful.

like image 961
gnash117 Avatar asked Feb 02 '23 06:02

gnash117


2 Answers

As for support for ANSI escape codes under Windows' cmd.exe, see ansicon. After translating your redirection logic to cmd.exe syntax I prepared the following color.bat file:

@Echo Off
(((%* 1>&3) 2>&1) | "c:\Program Files (x86)\GnuWin32\bin\sed.exe" "s,.*,\x1B[33m&\x1B[0m," 1>&2) 3>&1

Unfortunately the streams get mixed (on some lines the characters from stdout and stderr are mixed together in single line). Maybe this behavior depends on version of sed.exe used, so give it a try.

If this does not work, consider using a minimum cygwin install. I tested your color.sh script and I was able to launch a .bat file and it worked correctly without mixing streams. The syntax I used was:

./color.sh cmd /c test.bat
like image 120
MBu Avatar answered Feb 04 '23 20:02

MBu


I devised a method to get an equivalent solution using pure Batch commands, i.e. no Ansi, no sed.exe, etc., just findstr is used:

any_command 2>&1 1>&3 | findstr /N /A:4E "^"

In this case the different color is not given to the whole lines from stderr, but just to a line number provided by findstr that, however, should be enough for the stated requirements. I will write a small auxiliary .exe program soon that will show entire stderr lines in another color.

like image 26
Aacini Avatar answered Feb 04 '23 20:02

Aacini