虽然@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.