Batch SetLocal EnableDelayedExpansion and Math problems

…衆ロ難τιáo~ 提交于 2020-01-16 00:54:08

问题


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 =)


回答1:


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)


来源:https://stackoverflow.com/questions/33198978/batch-setlocal-enabledelayedexpansion-and-math-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!