Batch script : issue with colored echo when chaining commands

Viewed 151

I am currently facing an issue when trying to echo some text in color with a batch script.

My issue only happens when I try to echo in color after another command (git command here) depending on the status code of the previous command : with && or ||.

Example:

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

echo %ESC%[92mGreen%ESC%[0m
echo %ESC%[91mRed%ESC%[0m
echo %ESC%[92mGreen%ESC%[0m && echo %ESC%[91mRed%ESC%[0m
git pull || echo %ESC%[92mGreen%ESC%[0m && echo %ESC%[91mRed%ESC%[0m

pause

enter image description here

As you can see, echo in color doesn't work anymore after my git pull command. This will be the same if I use && instead of || and if git pull returns success.

Any idea ?

Thanks.

1 Answers

Just call labels and have the colors referenced inside the labels:

@echo off
cls
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
call :green
call :red
git pull && call :green || call :red

goto :eof
:green
echo %ESC%[92mSuccess%ESC%[0m
goto :eof
:red
echo %ESC%[91mFailed%ESC%[0m
goto :eof

And the result:

enter image description here

Note the sequence of the conditional operators are:

command && errorlevel is 0 || errorlevel is larger than 0

in other words, command and if successful or if not successful

Related