By rui


2010-01-12 11:28:01 8 Comments

I know that the color bf command sets the colors of the whole command line window but I wanted to to print one single line in a different color.

17 comments

@PavDub 2020-01-23 08:42:40

There is an accepted answer with more than 250 upvotes already. The reason I am still contributing is that the escape character required for echoing is not accepted by many editors (I am using, e.g., MS Code) and all other solutions require some third-party (non-Windows-default) pieces of software.

The work-around with using only plain batch commands is using PROMPT instead of ECHO. The PROMPT command accepts the escape character in an any-editor-friendly way as a $Echaracter sequence. (Simply replace the Esc in the ASCII Escape codes) with $E.

Here is a demo code:

@ECHO OFF

    :: Do not pollute environment with the %prompt.bak% variable
    :: ! forgetting ENDLOCAL at the end of the batch leads to prompt corruption
    SETLOCAL

    :: Old prompt settings backup
    SET prompt.bak=%PROMPT%

    :: Entering the "ECHO"-like section

        :: Forcing prompt to display after every command (see below)
        ECHO ON

        :: Setting the prompt using the ANSI Escape sequence(s)
        :: - Always start with $E[1A, otherwise the text would appear on a next line
        :: - Then the decorated text follows
        :: - And it all ends with $E30;40m, which makes the following command invisible
        ::   - assuming default background color of the screen
        @ PROMPT $E[1A$E[30;42mHELLO$E[30;40m

        :: An "empty" command that forces the prompt to display. 
        :: The word "rem" is displayed along with the prompt text but is made invisible
        rem

        :: Just another text to display
        @ PROMPT $E[1A$E[33;41mWORLD$E[30;40m
        rem

        :: Leaving the "ECHO"-like section
        @ECHO OFF

    :: Or a more readable version utilizing the cursor manipulation ASCII ESC sequences

        :: the initial sequence
        PROMPT $E[1A
        :: formating commands
        PROMPT %PROMPT%$E[32;44m
        :: the text
        PROMPT %PROMPT%This is an "ECHO"ed text...
        :: new line; 2000 is to move to the left "a lot"
        PROMPT %PROMPT%$E[1B$E[2000D
        :: formating commands fro the next line
        PROMPT %PROMPT%$E[33;47m
        :: the text (new line)
        PROMPT %PROMPT%...spreading over two lines
        :: the closing sequence
        PROMPT %PROMPT%$E[30;40m

        :: Looks like this without the intermediate comments:
        :: PROMPT $E[1A
        :: PROMPT %PROMPT%$E[32;44m
        :: PROMPT %PROMPT%This is an "ECHO"ed text...
        :: PROMPT %PROMPT%$E[1B$E[2000D
        :: PROMPT %PROMPT%$E[33;47m
        :: PROMPT %PROMPT%...spreading over two lines
        :: PROMPT %PROMPT%$E[30;40m

        :: show it all at once!
        ECHO ON
        rem
        @ECHO OFF

    :: End of "ECHO"-ing

    :: Setting prompt back to its original value
    :: - We prepend the settings with $E[37;40m in case
    ::   the original prompt settings do not specify color
    ::   (as they don't by default).
    :: - If they do, the $E[37;40m will become overridden, anyway.
    :: ! It is important to write this command 
    ::   as it is with `ENDLOCAL` and in the `&` form.
    ENDLOCAL & PROMPT $E[37;40m%prompt.bak%

EXIT /B 0

NOTE: The only drawback is that this technique collides with user cmd color settings (color command or settings) if not known explicitly.

-- Hope this helps as thi is the only solution acceptable for me for the reasons mentioned at the beginning. --

EDIT:

Based on comments, I am enclosing another snippet inspired by @Jeb. It:

  • Shows how to obtain and use the "Esc" character runtime (rather than entering it to an editor) (Jeb's solution)
  • Uses "native" ECHO command(s)
  • So it does not affect local PROMPT value
  • Demonstrates that coloring the ECHO output inevitably affect PROMPT color so the color must be reset, anyway
@ECHO OFF

    :: ! To observe color effects on prompt below in this script
    ::   run the script from a fresh cmd window with no custom
    ::   prompt settings

    :: Only not to pollute the environment with the %\e% variable (see below)
    :: Not needed because of the `PROMPT` variable
    SETLOCAL

        :: Parsing the `escape` character (ASCII 27) to a %\e% variable
        :: Use %\e% in place of `Esc` in the [http://ascii-table.com/ansi-escape-sequences.php]
        FOR /F "delims=#" %%E IN ('"prompt #$E# & FOR %%E IN (1) DO rem"') DO SET "\e=%%E"

        :: Demonstrate that prompt did not get corrupted by the previous FOR
        ECHO ON
        rem : After for
        @ECHO OFF

        :: Some fancy ASCII ESC staff
        ECHO [          ]
        FOR /L %%G IN (1,1,10) DO (
            TIMEOUT /T 1 > NUL
            ECHO %\e%[1A%\e%[%%GC%\e%[31;43m.
            ECHO %\e%[1A%\e%[11C%\e%[37;40m]
        )

        :: ECHO another decorated text
        :: - notice the `%\e%[30C` cursor positioning sequence
        ::   for the sake of the "After ECHO" test below
        ECHO %\e%[1A%\e%[13C%\e%[32;47mHELLO WORLD%\e%[30C

        :: Demonstrate that prompt did not get corrupted by ECHOing
        :: neither does the cursor positioning take effect.
        :: ! But the color settings do.
        ECHO ON
        rem : After ECHO
        @ECHO OFF

    ENDLOCAL

    :: Demonstrate that color settings do not reset
    :: even when out of the SETLOCAL scope
    ECHO ON
    rem : After ENDLOCAL
    @ECHO OFF

    :: Reset the `PROMPT` color
    :: - `PROMPT` itself is untouched so we did not need to backup it.
    :: - Still ECHOING in color apparently collide with user color cmd settings (if any).
    :: ! Resetting `PROMPT` color this way extends the `PROMPT`
    ::   by the initial `$E[37;40m` sequence every time the script runs.
    :: - Better solution then would be to end every (or last) `ECHO` command
    ::   with the `%\e%[37;40m` sequence and avoid setting `PROMPT` altogether.
    ::   which makes this technique preferable to the previous one (before EDIT)
    :: - I am keeping it this way only to be able to
    ::   demonstrate the `ECHO` color effects on the `PROMPT` above.
    PROMPT $E[37;40m%PROMPT%

    ECHO ON
    rem : After PROMPT color reset
    @ECHO OFF

EXIT /B 0

@VonC 2020-01-23 09:20:19

Very interesting technique. I will see if I need to update github.com/VonC/batcolors with it. Upvoted.

@jeb 2020-01-23 09:48:53

@VonC You can simply create a variable, containing the escape chatacter, without the need to enter it into the editor. for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "\e=%%E"

@VonC 2020-01-23 09:55:08

@jeb Do you mean "as opposed to echo used in batcolors/echo.bat"?

@jeb 2020-01-23 10:04:30

@VonC Yes, replace your set ASCII27=← with for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "ASCII27=%%E". This uses the escape character created by the prompt command, without changing the prompt permanently (because the prompt command is executed in a child process). Btw. Your echos.bat has some optimization potential ...

@VonC 2020-01-23 10:09:38

@jeb "Your echos.bat has some optimization potential": I am sure of it :) Pull Requests are welcome (both for the ASCII27 and other optimisations)

@jeb 2020-01-23 10:13:03

@VonC I'm working on it ... coming soon

@VonC 2020-01-23 10:14:33

@jeb Thank you in advance. test_colors.bat will allow you to check if everything is still working.

@jeb 2020-01-23 10:19:35

@PavDub 2020-01-23 19:58:05

1) Wow, I would not expect this topic be so hot! :) My solution comes from the good old "no-for" days, still I like the trick of obtaining the ASCII27 character (I guess I would not reveal it myself) 2) It seems that the ECHO-ed version still inevitably changes prompt collor settings (even with SETLOCAL) so that resetting the prompt collor is needed at the end. (eddited my post)

@VonC 2020-01-23 21:36:48

@PavDub Thank you for your answer: here is the result, thanks to jeb's expertise: github.com/VonC/batcolors

@Gringo Suave 2018-10-05 20:06:12

Windows 10 - TH2 and above:

(a.k.a. Version 1511, build 10586, release 2015-11-10)

At Command Prompt:

echo ^[[32m HI ^[[0m

Using the actual keys:   echo Ctrl+[[32m HICtrl+[[0mEnter

You should see a green "HI" below it.

Code numbers can be found here:

Notepad:

To save this into notepad, you can type ESC into it using: Alt+027 with the numpad, then the [32m part. Another trick when I was on a laptop, redirect the line above into a file to get started, then cut and paste:

echo echo ^[[32m HI ^[[0m >> batch_file.cmd

@Aleksander Stelmaczonek 2018-12-01 11:30:34

Alt + 027 was exactly what I needed!

@derHugo 2019-07-22 09:24:28

Alt+027 dosn't work in Eclipse/Java .. also tried \033 but nope ... how could I do this in Java?

@Bryan Ash 2012-01-19 03:49:27

You could use ANSICON to enable ANSI terminal codes in older versions of Windows. There are 32 and 64 bit versions that I have used in Windows XP and Windows 7.

@EHerman 2014-06-12 15:19:36

Can't get it to work on windows 8.1. Crashing everytime I try and install.

@Bryan Ash 2014-06-13 13:32:09

@EHerman Maybe this question will help.

@Gringo Suave 2019-07-31 21:07:30

ANSICON is not needed in later versions of Win 10. Don't try to use it there.

@dan tauro 2013-01-21 21:13:44

You can use the color command to change the color of the whole console

Color 0F

Is black and white

Color 0A 

Is black and green

@Luke 2013-07-18 14:58:50

Nice to know. Unfortunately this changes the color of the whole console and the question is how to change a single line (or a part of it)..

@Randall Flagg 2014-10-23 05:25:54

The OP has stated that he is familiar with this command and that the problem is that it changes the entire console and not a specific line.

@CuriousMarc 2015-08-17 07:57:29

Yes indeed not truly responsive, but that's still useful to know.

@Jens A. Koch 2016-07-27 15:22:24

I wanted to to print one single line in a different color.

Use ANSI Escape Sequences.

Windows before 10 - no native support for ANSI colors on the console

For Windows version below 10, the Windows command console doesn't support output coloring by default. You could install either Cmder, ConEmu, ANSICON or Mintty (used by default in GitBash and Cygwin) to add coloring support to your Windows command console.

Windows 10 - Command Line Colors

Starting from Windows 10 the Windows console support ANSI Escape Sequences and some colors by default. The feature shipped with the Threshold 2 Update in Nov 2015.

MSDN Documentation

Update (05-2019): The ColorTool enables you to change the color scheme of the console. It's part of the Microsoft Terminal project.

Demo

enter image description here

Batch Command

The win10colors.cmd was written by Michele Locati:

@echo off
cls
echo [101;93m STYLES [0m
echo ^<ESC^>[0m [0mReset[0m
echo ^<ESC^>[1m [1mBold[0m
echo ^<ESC^>[4m [4mUnderline[0m
echo ^<ESC^>[7m [7mInverse[0m
echo.
echo [101;93m NORMAL FOREGROUND COLORS [0m
echo ^<ESC^>[30m [30mBlack[0m (black)
echo ^<ESC^>[31m [31mRed[0m
echo ^<ESC^>[32m [32mGreen[0m
echo ^<ESC^>[33m [33mYellow[0m
echo ^<ESC^>[34m [34mBlue[0m
echo ^<ESC^>[35m [35mMagenta[0m
echo ^<ESC^>[36m [36mCyan[0m
echo ^<ESC^>[37m [37mWhite[0m
echo.
echo [101;93m NORMAL BACKGROUND COLORS [0m
echo ^<ESC^>[40m [40mBlack[0m
echo ^<ESC^>[41m [41mRed[0m
echo ^<ESC^>[42m [42mGreen[0m
echo ^<ESC^>[43m [43mYellow[0m
echo ^<ESC^>[44m [44mBlue[0m
echo ^<ESC^>[45m [45mMagenta[0m
echo ^<ESC^>[46m [46mCyan[0m
echo ^<ESC^>[47m [47mWhite[0m (white)
echo.
echo [101;93m STRONG FOREGROUND COLORS [0m
echo ^<ESC^>[90m [90mWhite[0m
echo ^<ESC^>[91m [91mRed[0m
echo ^<ESC^>[92m [92mGreen[0m
echo ^<ESC^>[93m [93mYellow[0m
echo ^<ESC^>[94m [94mBlue[0m
echo ^<ESC^>[95m [95mMagenta[0m
echo ^<ESC^>[96m [96mCyan[0m
echo ^<ESC^>[97m [97mWhite[0m
echo.
echo [101;93m STRONG BACKGROUND COLORS [0m
echo ^<ESC^>[100m [100mBlack[0m
echo ^<ESC^>[101m [101mRed[0m
echo ^<ESC^>[102m [102mGreen[0m
echo ^<ESC^>[103m [103mYellow[0m
echo ^<ESC^>[104m [104mBlue[0m
echo ^<ESC^>[105m [105mMagenta[0m
echo ^<ESC^>[106m [106mCyan[0m
echo ^<ESC^>[107m [107mWhite[0m
echo.
echo [101;93m COMBINATIONS [0m
echo ^<ESC^>[31m                     [31mred foreground color[0m
echo ^<ESC^>[7m                      [7minverse foreground ^<-^> background[0m
echo ^<ESC^>[7;31m                   [7;31minverse red foreground color[0m
echo ^<ESC^>[7m and nested ^<ESC^>[31m [7mbefore [31mnested[0m
echo ^<ESC^>[31m and nested ^<ESC^>[7m [31mbefore [7mnested[0m

@user3057544 2017-01-18 11:00:15

@Jens A. Koch - it is not working in my windows 10 console ( cmd )

@Jens A. Koch 2017-01-18 11:47:58

That's odd, but a local problem. 1) Make sure you have Windows 10 with the Threshold 2 update (Nov 2015). It's needed for color support. ( It's working. Just tested with Version 10.0.14393.) --- 2) You saved the content to a file colors.cmd and ran that, right?

@user3057544 2017-01-18 12:25:02

@Jens A. Koch 1) I am using Windows 10 Pro, Version 1607, OS Build 14393.693 2) I have file .bat not .cmd - can I use .bat not .cmd ?

@Jens A. Koch 2017-01-18 12:32:49

Ok. Thanks for the feedback. .cmd or .bat - both should work. But, i think i know why it doesn't work: it seems the escape symbol is removed when posting to StackOverflow. Please do not copy the content from my answer, use the content from here instead: gist.githubusercontent.com/mlocati/…

@user3057544 2017-01-18 13:43:08

@Jens A. Koch yes, you are right - now it works, thanks a lot!

@kayleeFrye_onDeck 2017-01-21 06:45:28

I never had to generate a ESC in notepad++ before... You can do this with ALT-codes using the numpad and the left ALT key: L-ALT+0+2+7

@kayleeFrye_onDeck 2017-01-21 08:07:56

Btw, as someone who makes and uses a lot batches most days, this answer has enhanced my overall toolset in an aesthetic way! Using VB? Hell no. This is the way to go!

@Aacini 2017-04-22 14:10:21

You can generate an ESC character in a Batch file this way: for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"

@Qwerty 2017-05-18 13:11:16

This seem to not work any more in newer versions of Windows 10... SO question

@kayleeFrye_onDeck 2017-08-21 07:57:25

@Qwerty it still works in Creator's Update, but one of the updates seems to have caused a bug that can make triggering it more difficult if it is a consumed script. You might need to start using a shim or calling your scripts with an extra switch, depending on what shells you're planning on supporting with coloration. I ran into a similar problem: stackoverflow.com/a/45449530/3543437

@chersun 2018-04-22 21:36:11

@JensA.Koch This is awesome. But I have a problem with it running in a for loop. Only the first echo gets properly colored, after that all other ones just print all escape characters instead of changing anything. Batch file is to archive each folder to separate archive, trying to ouput folder name in bold, followed by archiver standard output with findstr filtering.

@Mark Deven 2019-01-19 15:09:13

You can change the color without creating a new line: echo | set /p="ESCAPECHARACTER[91m"

@Zarepheth 2019-06-12 19:51:21

When executing my script (a *.cmd file), the escape sequences only work on the first echo statement. After this, the esc character is rendered with the unknown character symbol, along with the rest of the escape sequence and the sequence is not processed. @Aacini method to generate the escape works just as well as using Notepad++ and the key sequence of Alt+0, Alt+2, Alt+7. I am guessing there is a bug in the console window's terminal emulation.

@Zeek2 2019-12-20 11:51:18

@kayleeFrye_onDeck Thanks for posting a Notepad++ workaround for inserting the ESC. It was a bit finickey for me, I think the NUM-lock state is important (but my Microsoft keyboard doesn't have an LED to show its state, so can't say which state worked!).

@Zeek2 2019-12-20 12:08:14

Works for the first echo in my for-loop but not subsequent iterations, where the escape characters are instead displayed as a special character, small P or ? in a rectangular box :(

@kayleeFrye_onDeck 2019-12-20 21:10:12

@Zeek2 check this gist. You might need to manually replace the special characters using alt codes, and yes the numpad being enabled as well as using the numbers only from the numpad does matter: gist.github.com/the-nose-knows/fdccf686c5d017094fa76e805b2b0‌​5d6

@sangner 2019-03-19 13:27:11

As Glenn Slayden said in this answer, you can add to the registry the proper value to make the cmd "more colorful".

Fortunately, the global default can be changed from opt-in to opt-out. The registry key at HKEY_CURRENT_USER\Console\VirtualTerminalLevel sets the global default behavior for processing ANSI escape sequences. Create a DWORD key (if necessary) and set its value to 1 to globally enable (or 0 to disable`) ANSI processing by default.

@Josem 2019-02-10 21:51:58

An alternative is to use NodeJS.

Here is an example:

const os = require('os');
const colors = require('colors');

console.log("Operative System:".green,os.type(),os.release());
console.log("Uptime:".blue,os.uptime());

And this is the result:

enter image description here

@Iain 2011-08-04 13:30:02

This isn't a great answer, but if you know the target workstation has Powershell you can do something like this (assuming BAT / CMD script):

CALL:ECHORED "Print me in red!"

:ECHORED
%Windir%\System32\WindowsPowerShell\v1.0\Powershell.exe write-host -foregroundcolor Red %1
goto:eof

Edit: (now simpler!)

It's an old answer but I figured I'd clarify & simplify a bit

img

PowerShell is now included in all versions of Windows since 7. Therefore the syntax for this answer can be shortened to a simpler form:

  • the path doesn't need to be specified since it should be in the environment variable already.
  • unambiguous commands can be abbreviated. For example you can:
    • use -fore instead of -foregroundcolor
    • use -back instead of -backgroundcolor
  • the command can also basically be used 'inline' in place of echo
    (rather than creating a separate batch file as above).

Example:

powershell write-host -fore Cyan This is Cyan text
powershell write-host -back Red This is Red background

More Information:

The complete list of colors and more information is available in the
- PowerShell Documentation for Write-Host

@wener 2014-01-05 18:37:12

Greate,it works for me,but it's tooooooooooooooo slow.

@SgtPooki 2014-05-08 19:59:18

i realize that this is an answer providing a solution, but powershell? ugh.

@Iain 2014-05-14 12:48:51

That's why I started with "This isn't a great answer". I quite like Powershell but it's overkill for this. ANSICON is better if you can cope with deploying it to the target machines.

@pizzafilms 2018-04-08 18:22:37

Thank you for this answer. I've looked high and low for a way to echo colored output from a batch file in Powershell and this was the only one. Not sure why it takes so long to actually print it (there's like a 1 second wait with each call) but at least I can do it. Thank you!

@npocmaka 2015-01-31 10:53:09

This is a self-compiled bat/.net hybrid (should be saved as .BAT) that can be used on any system that have installed .net framework (it's a rare thing to see an windows without .NET framework even for the oldest XP/2003 installations) . It uses jscript.net compiler to create an exe capable to print strings with different background/foreground color only for the current line.

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

%~n0.exe %*

endlocal & exit /b %errorlevel%

*/

import System;

var arguments:String[] = Environment.GetCommandLineArgs();

var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;


//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
  'n': '\n',
  'r': '\r',
  't': '\t',
  'f': '\f',
  'v': '\v',
  'b': '\b'
};

function decodeJsEscape(_, hex0, hex1, octal, other) {
  var hex = hex0 || hex1;
  if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
  if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
  return jsEscapes[other] || other;
}

function decodeJsString(s) {
  return s.replace(
      // Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
      // octal in group 3, and arbitrary other single-character escapes in group 4.
      /\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
      decodeJsEscape);
}


function printHelp( ) {
   print( arguments[0] + "  -s string [-f foreground] [-b background] [-n] [-e]" );
   print( " " );
   print( " string          String to be printed" );
   print( " foreground      Foreground color - a " );
   print( "                 number between 0 and 15." );
   print( " background      Background color - a " );
   print( "                 number between 0 and 15." );
   print( " -n              Indicates if a new line should" );
   print( "                 be written at the end of the ");
   print( "                 string(by default - no)." );
   print( " -e              Evaluates special character " );
   print( "                 sequences like \\n\\b\\r and etc ");
   print( "" );
   print( "Colors :" );
   for ( var c = 0 ; c < 16 ; c++ ) {

        Console.BackgroundColor = c;
        Console.Write( " " );
        Console.BackgroundColor=currentBackground;
        Console.Write( "-"+c );
        Console.WriteLine( "" );
   }
   Console.BackgroundColor=currentBackground;



}

function errorChecker( e:Error ) {
        if ( e.message == "Input string was not in a correct format." ) {
            print( "the color parameters should be numbers between 0 and 15" );
            Environment.Exit( 1 );
        } else if (e.message == "Index was outside the bounds of the array.") {
            print( "invalid arguments" );
            Environment.Exit( 2 );
        } else {
            print ( "Error Message: " + e.message );
            print ( "Error Code: " + ( e.number & 0xFFFF ) );
            print ( "Error Name: " + e.name );
            Environment.Exit( 666 );
        }
}

function numberChecker( i:Int32 ){
    if( i > 15 || i < 0 ) {
        print("the color parameters should be numbers between 0 and 15");
        Environment.Exit(1);
    }
}


if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help"   ) {
    printHelp();
    Environment.Exit(0);
}

for (var arg = 1; arg <= arguments.length-1; arg++ ) {
    if ( arguments[arg].toLowerCase() == "-n" ) {
        newLine=true;
    }

    if ( arguments[arg].toLowerCase() == "-e" ) {
        evaluate=true;
    }

    if ( arguments[arg].toLowerCase() == "-s" ) {
        output=arguments[arg+1];
    }


    if ( arguments[arg].toLowerCase() == "-b" ) {

        try {
            backgroundColor=Int32.Parse( arguments[arg+1] );
        } catch(e) {
            errorChecker(e);
        }
    }

    if ( arguments[arg].toLowerCase() == "-f" ) {
        try {
            foregroundColor=Int32.Parse(arguments[arg+1]);
        } catch(e) {
            errorChecker(e);
        }
    }
}

Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;

if ( evaluate ) {
    output=decodeJsString(output);
}

if ( newLine ) {
    Console.WriteLine(output);  
} else {
    Console.Write(output);

}

Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;

Here's the help message:

enter image description here

Example:

coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e

You can also find this script here.

You can also check carlos' color function -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

@Graham 2015-06-30 15:16:43

How cool is that. A bat file that compiles the jscript that is in it and only if it needs to - I'm well impressed. Didn't even know there was a jscript compiler just sitting there waiting to be used. You get my "awesome award" for the month. You ought to mention that the first use of it will be slow (because of the compile).

@EM0 2015-12-10 14:25:37

I don't need colour badly enough to go to this extreme, but the technique is really impressive and I can see myself using that elsewhere.

@Tutankhamen 2014-04-15 00:09:45

You can just creates files with the name of the word to print, uses findstr which can print in color, and then erases the file. Try this example:

@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)

call :ColorText 0a "green"
call :ColorText 0C "red"
call :ColorText 0b "cyan"
echo(
call :ColorText 19 "blue"
call :ColorText 2F "white"
call :ColorText 4e "yellow"

goto :eof

:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof

Run color /? to get a list of colors.

@FeatureCreep 2014-07-05 03:40:46

This sets colors in windows command line. Could you explain what it does?

@FeatureCreep 2014-07-16 07:58:26

Ok, it just creates files with the name of the word to print, uses findstr which can print in color, and then erases the file.

@yoyo 2015-01-21 22:02:23

That is impressive! Note that the colour codes are wrong. Run "color /?" to see the actual colour codes.

@yoyo 2015-01-21 22:15:47

Note that findstr can only colourize the filename, which means you can't use this trick for strings that contain illegal path characters.

@jeb 2015-03-12 17:37:30

It can handle all characters you only need to modify the filename, SO:How to have multiple colors in a batch file?

@BrainSlugs83 2015-12-10 20:30:57

@jeb not all characters are legal filename characters (slashes, quotes, asterisk, and question mark for example).

@BrainSlugs83 2015-12-10 20:43:22

Also of note, this will overwrite files in the same directory if they share the name of what you're trying to print... that's not good at all.

@jeb 2015-12-11 07:08:49

@BrainSlugs83 I know that not all characters are vaild, but they are allowed in the filename when they are in front of \..`. And I don't overwrite files, the only file I create is named X`. This post is only the copy of my first solution, indeed that can overwrite existing files

@StefansArya 2017-10-30 02:43:00

My files was deleted because of this

@Micha Wiedenmann 2018-01-17 15:05:35

Did you just take it from stackoverflow.com/questions/4339649/…? If so, you should probably mention it.

@Michel de Groot 2017-07-12 10:16:58

To get this working on Windows 10, you can enable this flag: ENABLE_VIRTUAL_TERMINAL_PROCESSING.

With this registry key you can set this by default

[HKCU\Console] VirtualTerminalLevel dword 0x1

@user6017774 2017-01-01 21:55:05

Put the following lines into a file called ColourText.bas on your desktop.

Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32

Public Module MyApplication  
Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" (ByVal nStdHandle As Long) As Long
Public Declare Function SetConsoleTextAttribute Lib "kernel32" Alias "SetConsoleTextAttribute" (ByVal hConsoleOutput As Long, ByVal wAttributes As Long) As Long
Public Const STD_ERROR_HANDLE = -12&
Public Const STD_INPUT_HANDLE = -10&
Public Const STD_OUTPUT_HANDLE = -11&

Sub Main()
    Dim hOut as Long
    Dim Ret as Long
    Dim Colour As Long
    Dim Colour1 As Long
    Dim Text As String
    hOut  = GetStdHandle(STD_OUTPUT_HANDLE)
    Colour = CLng("&h" & Split(Command(), " ")(0))
    Colour1 = Clng("&h" & Split(Command(), " ")(1))
    Text = Mid(Command(), 7)
    Ret = SetConsoleTextAttribute(hOut,  Colour)
    Console.Out.WriteLine(text)
    Ret = SetConsoleTextAttribute(hOut, Colour1)
End Sub
End Module

Save it and type the following in a command prompt.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%userprofile%\desktop\ColourText.exe" "%userprofile%\desktop\ColourText.bas" /verbose

A file called ColourText.exe will appear on your desktop. Move it to the Windows folder.

To use you must use two character codes to set colour eg 01 not 1.

ColourText ColourOfText ColourOfTextWhenFinished Text

EG To set blue on white by not passing any text, then red on white text, finishing with blue on grey.

ColourText F1 F1
ColourText F2 71 This is green on white

or

ColourText F1 F1
cls
ColourText F4 F4
Echo Hello
Echo Hello today
ColourText F1 F1

Also the CLS command becomes interesting. Color command without parameters resets all colours to startup colours.

To get the colour code add the following numbers together. Use Calculator in programmers mode. These are hex numbers. They can be added together eg Red + Blue + FG Intensity = 13 = D. As 10+ wasn't used the background will be black. Colour codes MUST be two characters, eg 08 not 8.

FOREGROUND_RED = &H4     '  text color contains red.
FOREGROUND_INTENSITY = &H8     '  text color is intensified.
FOREGROUND_GREEN = &H2     '  text color contains green.
FOREGROUND_BLUE = &H1     '  text color contains blue.
BACKGROUND_BLUE = &H10    '  background color contains blue.
BACKGROUND_GREEN = &H20    '  background color contains green.
BACKGROUND_INTENSITY = &H80    '  background color is intensified.
BACKGROUND_RED = &H40    '  background color contains red.

@Abel 2017-09-28 03:06:23

While interesting, not everyone will have the SDK installed, in fact, very few people, I think.

@Nick-n-Chicago 2015-02-09 05:00:46

I looked at this because I wanted to introduce some simple text colors to a Win7 Batch file. This is what I came up with. Thanks for your help.

@echo off
cls && color 08

rem .... the following line creates a [DEL] [ASCII 8] [Backspace] character to use later
rem .... All this to remove [:]
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (set "DEL=%%a")

echo.

<nul set /p="("
call :PainText 09 "BLUE is cold"    && <nul set /p=")  ("
call :PainText 02 "GREEN is earth"  && <nul set /p=")  ("
call :PainText F0 "BLACK is night"  && <nul set /p=")"
echo.
<nul set /p="("
call :PainText 04 "RED is blood"    && <nul set /p=")  ("
call :PainText 0e "YELLOW is pee"   && <nul set /p=")  ("
call :PainText 0F "WHITE all colors"&& <nul set /p=")"

goto :end

:PainText
<nul set /p "=%DEL%" > "%~2"
findstr /v /a:%1 /R "+" "%~2" nul
del "%~2" > nul
goto :eof

:end
echo.
pause

@Olegs Jeremejevs 2014-02-13 11:59:34

I was annoyed by the lack of proper coloring in cmd too, so I went ahead and created cmdcolor. It's just an stdout proxy, which looks for a limited set of ANSI/VT100 control sequences (in other words, like in bash), i.e. echo \033[31m RED \033[0m DEFAULT | cmdcolor.exe.

Usage and downloads.

@paddy 2014-02-19 01:15:49

This is cool, and I've put it into the menu system of a giant build script at my work. Only beef I have is that the binary you provide on that page targets 64-bit, so it won't work on our 32-bit build machine. But it was no problem just grabbing the source and compiling myself.

@Olegs Jeremejevs 2014-02-19 09:52:33

But it's 32-bit :) Here's the output of GNU file: cmdcolor.exe; PE32 executable for MS Windows (console) Intel 80386 32-bit

@paddy 2014-02-19 21:10:39

That's odd... XP Pro refused to run it, but it ran fine on my Win7 64 box. I compiled with Visual C++, targeting Win32, and it was fine.

@Olegs Jeremejevs 2014-02-19 21:46:36

Huh... probably because of upx. Could you contact me via e-mail, please?

@Brian Gleason 2010-06-01 19:54:05

you could use cecho.. you can also use it to embed right into your script so you dont have to carry along a .com or .exe

http://www.codeproject.com/Articles/17033/Add-Colors-to-Batch-Files

@Michael J 2010-01-12 11:32:02

We used to do this with ANSI terminal codes. Not sure if they still work, but you could try them.

@Davor Josipovic 2015-09-24 07:13:20

This could be a good answer if it explained how to use these ANSI terminal codes...

@Michael J 2015-09-27 00:03:47

I thought the article I linked to explained it. Did you read that? BTW:it says they don't work on win32.

@Davor Josipovic 2015-09-28 07:49:45

Diagonally. The article explains what ANSI terminal codes are, but not really how to used them from within cmd, so to answer the question. (Yes... the fact that Win32 console is not supported makes them a bit irrelevant for the question.)

@Michael J 2015-09-29 04:14:03

You would just echo the ANSI codes to the terminal. e.g. "echo ←[6m" would set the terminal's text colour to 6 (red). Note "←" is ASCII 27 (escape). You could type it by holding down "ALT" and typing "27" on the numeric keypad. I just googled it and found out you can still use the "color" command to do the same thing (though the numeric codes are different). "color 4" gets you red text.

@Bernhard Hofmann 2010-01-12 11:30:45

You'll need to echo an ANSI escape code sequence to alter the text colour: http://en.wikipedia.org/wiki/ANSI_escape_code

Another very good source of these escape codes is http://ascii-table.com/ansi-escape-sequences.php

@rui 2010-01-12 11:41:43

That looks really promising but how do I emit the Escape character - ASCII 27 in an echo command?

@Joey 2010-01-12 16:50:44

The Windows console is no Terminal emulator. ANSI escape sequences simply can't work. You could coax Windows 9x into doing so by loading ANSI.SYS but we're a little past that by now.

Related Questions

Sponsored Content

37 Answered Questions

[SOLVED] How to install pip on Windows?

22 Answered Questions

[SOLVED] How to count lines in a document?

33 Answered Questions

[SOLVED] How do I parse command line arguments in Bash?

14 Answered Questions

[SOLVED] How to colorize diff on the command line?

47 Answered Questions

[SOLVED] How do I import an SQL file using the command line in MySQL?

30 Answered Questions

17 Answered Questions

[SOLVED] How do I run two commands in one line in Windows CMD?

27 Answered Questions

[SOLVED] How to change the output color of echo in Linux

24 Answered Questions

[SOLVED] Is there an equivalent of 'which' on the Windows command line?

7 Answered Questions

Sponsored Content