简体   繁体   中英

How to escape commands when comparing strings in batch file?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM