-1

I noticed that string comparison in a batch file doesn't work properly if you compare against words like "IF" and "DO".

IF "DO" == "DO" (
    ECHO YES
)

The above works fine, but isn't useful.

SET stringDO=DO
IF %stringDO% == "DO" (
    ECHO YES
) ELSE ( 
    ECHO NO
)

When we use a variable, the result for the above example is "NO"

Strangely, comparing 2 variables works fine.

SET stringDO=DO
SET compare=DO
IF %stringDO% == %compare% (
    ECHO YES
)

So my question is, am I doing anything wrong or is this an intended behavior?

Is there another way to escape command words in string comparisons?

Terence
  • 104
  • 6
  • 1
    Please take a look on answer on [Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files](https://stackoverflow.com/a/47386323/3074564) explaining in detail how string comparisons with command __IF__ work. The double quotes are included on comparing the two strings. So a string on left side without double quotes is definitely never equal a string on right side with double quotes. – Mofi Jan 03 '19 at 09:28
  • I recommend also reading [debugging a batch file](https://stackoverflow.com/a/42448601/3074564). On batch file coding it must be always taken into account how the line without or with an entire command block looks after parsing by Windows command processor as it can be seen on running the batch file from within a command prompt window without `@echo off` at top and not how it is written in the batch file. See also [How does the Windows Command Interpreter (CMD.EXE) parse scripts?](https://stackoverflow.com/questions/4094699/) – Mofi Jan 03 '19 at 09:32

1 Answers1

2

Question code if comparison evaluated in order:

  1. IF "DO" == "DO"
  2. IF DO == "DO"
  3. IF DO == DO

Double quotes are included in the comparison. DO does not equal "DO".

SET stringDO=DO
IF "%stringDO%" == "DO" (
    ECHO YES
) ELSE ( 
    ECHO NO
)

results in YES.

michael_heath
  • 5,042
  • 2
  • 9
  • 21