2

Running

@echo off
setlocal enabledelayedexpansion 
set x=some value with unsafe (^&^<^>()") characters inside
if 1 == 1 (
  echo "value of x (!x!) is interesting"
)

gives

"value of x (some value with unsafe (&<>()") characters inside) is interesting"

I had to put the value being echoed inside double quotes to avoid parsing error. I don't want these double quotes to be printed, however. Is there any way to temporarily (only to safely pass it to echo command) quote value being printed?

Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366

3 Answers3

2

you can add quotes to the variable and try a string substitution the moment you echo it. with e.g.:

echo %x:"=%

but in your case i dont think that will work. to make your example work just escape the parenthesis:

echo value of x ^(!x!^) is interesting

unfortunately there is no 100% answer for this.

let us know if it worked for you or you found a better solution

weberik
  • 2,636
  • 1
  • 18
  • 11
2

The answer is the same as in your question
How to escape variables with parentheses inside if-clause in a batch file?

@echo off
setlocal enabledelayedexpansion 
set x=some value with unsafe (^&^<^>()") characters inside
if 1 == 1 (
  set "output=value of x (!x!) is interesting"
  echo !output!
)
Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Well, it looks like this extended syntax of `set` with quotes is **the** building block of batch files... Is there any Microsoft document talking about this feature? – Piotr Dobrogost Oct 26 '11 at 16:58
2

Excuse me, I think there is a little confusion here.

If you want to print any special character with an echo command just escape it. Period. Your problem have no relation with Delayed Expansion. For example, this code:

@echo off
if 1 == 1 (
  echo value of x (anything) is interesting
)

mark an error because the parentheses in echo command interfere with the opened if. To solve this, just escape the parentheses as weberik said:

@echo off
if 1 == 1 (
  echo value of x ^(anything^) is interesting
)

A Delayed variable Expansion never cause an error don't matter the value inside the variable.

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • +1, for showing that the problem isn't the delayed expansion nor the special characters in `x` – jeb Oct 26 '11 at 12:37
  • I was very aware of the fact that neither contents of variable `x` nor the use of delayed expansion were the cause of a problem. :) I left them just to make sure what I present is as close to my real code as possible. That's because oversimplifying when creating a test case is so easy. – Piotr Dobrogost Oct 26 '11 at 16:37