1

Related: Using batch echo with special characters

How do I deal with using escape characters on text that might or mightn't be a special character?

Suppose we have user input:

Set /p var=prompt:

Now, I need to make sure that the text gets interpreted as text even if the user enters something like a special character. But I cannot simply add ^ before the variable...because that'd cancel the variable. The ^^%var% and ^%%var% options don't seem to work either.

How do I go about doing this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kravaros
  • 222
  • 3
  • 8
  • possible duplicate of [Escape characters in batch scripts](http://stackoverflow.com/questions/3854779/escape-characters-in-batch-scripts) – djechlin Dec 20 '13 at 01:56
  • 1
    @djechlin I dont think so, the solution there used TYPE command, which is not applicable in my case, as I am not reading from files. – Kravaros Dec 20 '13 at 02:01

2 Answers2

5

You should realize that the escapes are required in the source code of your program or when you expand a variable via %variable% or in the replaceable parameter of a for command. This is not required if you expand a variable via !delayed! expansion. So, your problem may be easily solved this way:

setlocal EnableDelayedExpansion

Set /p var=prompt:
echo !var!

The standard method to avoid the problem when you read a file that may have special characters is enclosing the value of the replaceable parameter in quotes when the value is asigned with Delayed Expansion disabled, and then Enable Delayed Expansion in order to manage the value. Of course, this method forces to insert an endlocal command inside the loop:

for /F "delims=" %%a in (anyFile.txt) do (
   set "line=%%a"
   setlocal EnableDelayedExpansion
   echo Line with special characters: !line!
   endlocal
)
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

Not possible. The shell processes the user input before your script does. Your script won't even know the user typed an escape character.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • The main problem isn't the user typing an escape character, but a special character, nevertheless, if I am correct to assume that it works the same, than thanks. – Kravaros Dec 20 '13 at 02:06
  • 2
    @djechin It's possible, see the answer of Aacini. And the escape characters are not processed, they will be assigned also to the variable. – jeb Dec 20 '13 at 06:19