Piotr Dobrogost
Piotr Dobrogost

Reputation: 42425

How to safely echo value of a variable inside if-clause skipping surrounding double quotes?

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?

Upvotes: 2

Views: 143

Answers (3)

Aacini
Aacini

Reputation: 67216

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.

Upvotes: 2

jeb
jeb

Reputation: 82277

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!
)

Upvotes: 2

weberik
weberik

Reputation: 2706

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

Upvotes: 2

Related Questions