derHugo
derHugo

Reputation: 90724

Hardcoding Ansii escape sequence for echo in batch file

I'm writin on a batch-file for windows with colored output using ANSII colors like

echo <ESC>[1m Some bold text <ESC>[0m
echo <ESC>[1;32m Some bold green text <ESC>[0m

From this answer and this table I know I have to use the ANSII code 27 character for <ESC> and I could copy it from the file the user linked.

This is working fine but I'm wondering if there is any option in batch to "hardcode" this sequence using "normal" (readable) characters as you do e.g in bash on linux

echo -e "\033[1;32m Red Bold Text \033[0m"

On this page I found some options how to insert the escape sequence. And I also read one can use

cmd /c exit 65
echo %=exitcodeAscii%

to print an A, but this seems not to work for

cmd /c exit 27
echo %=exitcodeAscii%[31m This would be supposed to be red, right?

How can I produce the escape sequence using code in a batchfile instead of inserting it by pressing certain key-combinations?

Upvotes: 1

Views: 2632

Answers (1)

jeb
jeb

Reputation: 82337

You can build your own echo-e.bat file echo -e equivalent in Windows?.

Or use a batch function instead.

call :echo-e "\x1b[1;31m Red Bold Text \x1b[0m"
exit /b

:echo-e
setlocal
set "arg1=%~1"
set "arg1=%arg1:\x=0x%"
forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(%arg1%"
exit /b

Creating a single escape character (27) you can use FORFILES or PROMPT

Like this sample

for /F "delims=#" %%a in ('prompt #$E# ^& for %%a in ^(1^) do rem') do set "esc=%%a"
echo %ESC%[1;31m Red Bold Text %ESC%[0m

Upvotes: 2

Related Questions