caspertone2003
caspertone2003

Reputation: 21

How to echo with different colors in the Windows command line INSIDE A FOR LOOP WITH A CHOICE cmd

While "How to echo with different colors in the Windows command line" is widely explained here

How to echo with different colors in the Windows command line

it fails inside a for loop, as chersun already noted:

@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. – chersun Apr 22 '18 at 21:36

I am opening a new question as I have not enough reputation to post in the above one.

Only solution I found was to include after the for command (inside the do block) a dummy CMD /C Echo/ as a workaround.

Are there any better ways?

TIA

Edit: Thanks for the comments, here goes the batch file

out of the block, colors go well. the issue goes with the CHOICE, if removed problem disapears. Solution is to include the "empty" CMD

Answer Y to the execution to see failed output

@ECHO OFF
for /F %%a in ('echo prompt $E ^| cmd') do set "_esc=%%a"
set _redon=%_esc%[91m
set _greenon=%_esc%[92m
set _coloff=%_esc%[0m
SET _free=1000
SET _used=2000
ECHO %_redon%!_used!%_coloff% / %_greenon%!_free!%_coloff%
SETLOCAL EnableDelayedExpansion
FOR /L %%A IN (1,1,5) DO (
    CHOICE /C YN /T 5 /D N /N /M "Press Y to process %%A"
    IF "!ERRORLEVEL!"=="1" (
        SET _free=1000
        SET _used=2000
REM needed CMD to return proper behaviour
REM     CMD /C echo/
        ECHO %_redon%!_used!%_coloff% / %_greenon%!_free!%_coloff%
    )
)
PAUSE
EXIT

Thanks to @Stephan for beautifying the code.

Upvotes: 2

Views: 3964

Answers (1)

user6811411
user6811411

Reputation:

I can't reproduce:

EDIT:changed to create the ESC symbol in a portable way, thanks to @Aacini

@echo off
cls
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"

echo ^<ESC^>[0m %ESC%[0mReset%ESC%[0m

for %%A in (
    7,30,31,32,33,34,35,36,37,
    40,41,42,43,44,45,46,47,
    90,91,92,93,94,95,96,97,
    100,101,102,103,104,105,106,107
) Do echo ^<ESC^>[%%Am %ESC%[%%AmTest%ESC%[0m

enter image description here

Upvotes: 2

Related Questions