8

When I try

@echo off
set PTag=^<BR^>
echo %PTag%

I get nothing.

Now what's interesting is that if there's an empty line after the last echo, I get:

The syntax of the command is incorrect.

If I remove the @echo off, then it actually outputs

echo <BR>

I want to add various HTML tags inside variables and then concatenate these variables to create an HTML that I will output in a file.

Axonn
  • 10,076
  • 6
  • 31
  • 43

3 Answers3

13

set PTag=^<BR^> sets the value <BR> to PTag

When you run echo %PTag% it expands to echo <BR> which is an invalid redirection. You need to escape the < and > inside PTag by using this

set PTag=^^^<BR^^^>

The first ^ escapes itself, then the next one escapes < or >

You can also use this

set "PTag=^<BR^>"

Reason for the second way: inside quotes ^ loses its special meaning

If it is a quote (") toggle the quote flag, if the quote flag is active, the following special characters are no longer special: ^ & | < > ( ).

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

most special characters (^ & ( ) < > | and also the standard delimiters , ; = SPACE TAB) lose their particular meaning as soon as ther are placed in between "", and the "" themselves do not become part of the variable value

Special Characters in Batch File


Now the variable will have the value ^<BR^> inside it, and it'll expand echo %PTag% to

echo ^<BR^>

which is a valid command

phuclv
  • 37,963
  • 15
  • 156
  • 475
5

Just quote your set:

set "PTag=^<BR^>"
echo %PTag%
Bali C
  • 30,582
  • 35
  • 123
  • 152
  • Thank you. Can you also add an explanation about the answer? I am not very good in batch, as it probably is obvious since I didn't know quotes can be used to wrap assignments. More precisely, I don't understand why the escape character works in quotes. When should one decide to use quotes around a command argument? – Axonn Apr 11 '17 at 14:54
  • 1
    Now that you mention it, I'm not entirely sure why, I just know it works :) Something about being escape characters, and being the line continuation character I think, this link might give you a better explanation http://www.robvanderwoude.com/escapechars.php – Bali C Apr 11 '17 at 15:00
2

Just use Delayed Expansion when you show the variable value:

@echo off
setlocal EnableDelayedExpansion

set "PTag=<BR>"
echo !PTag!
Aacini
  • 65,180
  • 12
  • 72
  • 108