In the following .BAT file, test 2 demonstrates the color bug inside a parenthesized block of code, test 3 demonstrates the bug inside a FOR loop, and test 4 shows how the bug can be mitigated by calling a do-nothing subroutine (call :resetANSI). My questions are:
What is the nature of the bug... why do inline color codes fail after the piping to FINDSTR within a parenthesized block of code? Is this bug specific to FINDSTR, or more general? (FINDSTR has some known bugs, but I didn't see this one listed among them.)
Is calling the do-nothing subroutine the best way to mitigate this bug?
Below the code is a screencapture of the display output, that shows the color code fails in tests 2 & 3 in the lines that are supposed to display in magenta.
Thanks in advance to whoever tries to help!
[EDIT 3/26/2020: Because the forum didn't display the Esc character in the colorcode definitions in the .bat code, I edited the .bat code so it will generate the Esc character at runtime.]
@echo off
goto :main
:resetANSI
EXIT /B
:main
setlocal EnableDelayedExpansion
for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "ESCchar=%%E"
set "green=%ESCchar%[92m"
set "yellow=%ESCchar%[93m"
set "magenta=%ESCchar%[95m"
set "cyan=%ESCchar%[96m"
set "white=%ESCchar%[97m"
echo %white%Test 1 is NOT in a FOR loop nor within parentheses.
echo %yellow%[Test 1] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
echo %cyan%Test 1 completed.
echo %white%Test 2 is within parentheses.
( echo %yellow%[Test 2] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 2 completed.
echo %white%Test 3 is within a FOR loop.
for /L %%G in (3,1,3) do (
echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 3 completed.%white%
echo %white%Test 4 is within a FOR loop and includes a call/return after the pipe to FINDSTR.
for /L %%G in (4,1,4) do (
echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
call :resetANSI
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 4 completed.%white%
exit /B

