Chris911
Chris911

Reputation: 4199

Escape quotes in batch script variable

How do you escape quotes in a variable to compare with another one.

Example: A script outputs "The output of "test.exe" is OK" (without the surrounding quotes)

In a batch script I save the output in a variable in my batch script and then want to compare with a saved variable.

set ouputTest1 = "The output of "test.exe" is OK"

test.exe -p 75 > temp.txt
set /p TESTOUTPUT=< temp.txt
if %TESTOUTPUT% == %ouputTest1%

The problem is with the outputTest1 variable and the quotes in the string. I tried with double quotes like this:

set ouputTest1 = "The output of ""test.exe"" is OK"

But with no luck.

Any ideas?

Upvotes: 3

Views: 4068

Answers (3)

jeb
jeb

Reputation: 82418

Your code has three problems:

Problem #1:

The line of script, set ouputTest1 = "The output of "test.exe" is OK" does not create a variable named outputTest1; instead it creates a variable named outputTest1<space>. This is the reason why %outputTest1% will always be empty.

Problem #2:

In a "set" statement, everything after the equal sign gets assigned--including the space and the outer quotes. In your case, the content of the variable winds up being <space>"The output of "test.exe" is OK".

Problem #3:

Finally, you need to change your IF-compare. The correct way to do it is as follows:

set "ouputTest1=The output of "test.exe" is OK"

test.exe -p 75 > temp.txt
set /p TESTOUTPUT=< temp.txt
if "%TESTOUTPUT%" == "%ouputTest1%" echo Equal

Upvotes: 6

Mattias Andersson
Mattias Andersson

Reputation: 2341

The answer that wmz has proposed seems like a solid one, but I thought I could still offer this alternative, for consideration.

Instead of reading the output (i.e. your temp.txt) into a variable, for comparison, you could instead write out your comparison string to another file and compare the files. Something like the following:

echo The output of "test.exe" is OK>temp-expected.txt
fc temp.txt temp.expected.txt >NUL
if "%ERRORLEVEL%"=="0" ( echo YAY ) else ( echo BOO )

Upvotes: 1

wmz
wmz

Reputation: 3685

Using delayed expansion seem to get round this, with or without surrounding quotes (c and d are unquoted):

@echo off
setlocal disabledelayedexpansion

set a="The output of "test.exe" is OK"
set b="The output of "test.exe" is OK"

set "c=The output of "test.exe" is NOT OK"
set "d=The output of "test.exe" is NOT OK"

setlocal enabledelayedexpansion
if !a!==!b! echo a and b match!
if !c!==!d! echo c and d match!

endlocal

Upvotes: 4

Related Questions