I’m trying to echo a string stored in a variable but it seems to require a lot of escaping. I’m trying with the following code:
setlocal EnableDelayedExpansion
@echo off
set "grass=@##&!$^&%**(&)"
echo !grass!
I want to echo the variable grass verbatim so I see a @##&!$^&%**(&) in the output. What should be done? Thanks!
echo !grass!will always echo the current value verbatim, without the need of any escaping. Your problem is, the value is not what you think it is! The problem is occurring when you are trying to SET the value.The correct escape sequence to set your value is
And now for the explanation. The information you need is buried in How does the Windows Command Interpreter (CMD.EXE) parse scripts?. But it is a bit hard to follow.
You have two problems:
1)
%must be escaped as%%for each time the line will be parsed. The presence or absence of quotes makes no difference. The delayed expansion state also makes no difference.2) A
!literal must be escaped as^!whenever it is parsed by the delayed expansion phase of the parser. If a line contains!anywhere within it during delayed expansion, then a^literal must be escaped as^^. But the^must also be either quoted or escaped as^^for the special character phase of the parser. This can be further complicated by the fact that a CALL will double up any^characters. (Sorry, it is very difficult to describe the problem, and the parser is complicated!)