简体   繁体   中英

Batch SetLocal EnableDelayedExpansion and Math problems

C:\WINDOWS\system32>SetLocal EnableDelayedExpansion
C:\WINDOWS\system32>set/a Number1=3+9
12
C:\WINDOWS\system32>if !Number1!==9+3 (echo Good) else (echo Bad)
Bad
C:\WINDOWS\system32>if !Number1!==3+9 (echo Good) else (echo Bad)
Bad
C:\WINDOWS\system32>set/a i=9+3
12
C:\WINDOWS\system32>if !Number1!==%i% (echo Good) else (echo Bad)
Bad

I expected to see the last results (and maybe some others) to show Good as a result but did not! I think this is because it is a error with the SetLocal EnableDelayedExpansion but I need that in my code. So how do I get my expected result with SetLocal EnableDelayedExpansion . Thanks for any help provided =)

setlocal EnableDelayedExpansion only works within batch files (see also setlocal /? ), it has no effect when being typed into command prompt; therefore the !! expansion does not work.

To use delayed expansion in command prompt, you need to open a new cmd instance:

cmd /V:ON

You cannot do arithmetics in the comparison expressions of the if statement directly, you need to do all the calculations in advance.
In addition, you should use the comparison operator EQU for numeric operations, because == forces string comparison:

set /A Number1=3+9
set /A i=9+3
if !Number1! EQU %i% (echo Good) else (echo Bad)

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