虽然@ ajv-jsy的答案大多数时候都有效,但我遇到的问题与@MarioVilas相同。如果要比较的字符串之一包含双引号(“),则变量扩展会引发错误。
例:
@echo off
SetLocal
set Lhs="
set Rhs="
if "%Lhs%" == "%Rhs%" echo Equal
错误:
echo was unexpected at this time.
解:
启用延迟扩展并使用!代替 %。
@echo off
SetLocal EnableDelayedExpansion
set Lhs="
set Rhs="
if !Lhs! == !Rhs! echo Equal
:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal
到目前为止,我还无法使用这种技术来打破它。它适用于空字符串和我扔给它的所有符号。
测试:
@echo off
SetLocal EnableDelayedExpansion
:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
if [%DevEnvDir%] == ["C:\..."]
。链接:stackoverflow.com/a/4953226/2428861