Well, there is no need to escape redirection operators and other special characters listed in last paragraph in help output by running cmd /?
in a command prompt window on last help page when the string to output is enclosed in double quotes.
But using "
on line with ECHO command results in having also the double quote output.
There are several solutions.
The first one is assigning the string to output to an environment variable and output the value of the environment variable using delayed expansion.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "Line=pipe = | and percent sign = %% and exclamation mark ^!"
echo !Line!
set "Line=redirection operators: < and > and >>"
echo !Line!
endlocal
Or a little bit shorter, but not so good readable:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "Line=pipe = | and percent sign = %% and exclamation mark ^!" & echo !Line!
set "Line=redirection operators: < and > and >>" & echo !Line!
endlocal
Note: %
and !
must be nevertheless escaped with another %
and with ^
to be interpreted as literal character in string assigned to environment variable Line
.
Another solution using a subroutine PrintLine
:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
call :PrintLine "pipe = | and percent sign = %%%% and exclamation mark !"
call :PrintLine "redirection operators: < and > and >>"
endlocal
goto :EOF
:PrintLine
set "Line=%~1"
setlocal EnableDelayedExpansion
echo !Line!
endlocal
goto :EOF
The disadvantages of this solution are:
- A percent sign must be defined with 4 percent signs to be finally printed as literal character.
- It is slower because of usage of SETLOCAL and ENDLOCAL on printing each line.
Read this answer for details about the commands SETLOCAL and ENDLOCAL.
One more solution according to comment by JosefZ uses command FOR for an implicit delayed expansion:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
for %%I in (
"pipe = | and percent sign = %% and exclamation mark !",
"redirection operators: < and > and >>"
) do echo %%~I
endlocal
The lines to output are specified in a comma separated list of double quoted strings for being processed by FOR.
It has the big advantage that just the percent sign must be escaped with an additional percent sign on delayed expansion being disabled. But the string to output can't contain a double quote with exception of ""
within string.
Thanks JosefZ for this contribution.
Other great solutions are provided by jeb in his answer.