Neo Mosaid
Neo Mosaid

Reputation: 419

Why is cmd batch IF with delayed expansion giving me the wrong result in a For loop?

Using delayed expansion inside for loop and if statement gives me incorrect results

@ECHO OFF  
SETLOCAL ENABLEDELAYEDEXPANSION
SET volume=k:
SET REQUIRED_SPACE=1073741824 
FOR /f "tokens=1* delims=:" %%i IN ('fsutil volume diskfree %volume%') DO (
    SET FREE_SPACE=%%j
)
SET FREE_SPACE=!FREE_SPACE: =!
IF NOT %FREE_SPACE% LSS %REQUIRED_SPACE% (
   ECHO %FREE_SPACE% not less %REQUIRED_SPACE%
)ELSE ECHO %FREE_SPACE%  less %REQUIRED_SPACE%

FOR /l %%A IN (1,1,1) DO (
    FOR /f "tokens=1* delims=:" %%i IN ('fsutil volume diskfree %volume%') DO (
       SET FREE_SPACE=%%j
     )
    SET FREE_SPACE=!FREE_SPACE: =!
    IF NOT !FREE_SPACE! LSS !REQUIRED_SPACE! (
         ECHO !FREE_SPACE! not less !REQUIRED_SPACE!
   )ELSE ECHO !FREE_SPACE!  less !REQUIRED_SPACE!
)
pause

result is :

268685312  less 1073741824
268685312 not less 1073741824
Press any key to continue . . .

I don't understand what's wrong.

Upvotes: 2

Views: 161

Answers (1)

Magoo
Magoo

Reputation: 79983

A space between the close-parenthesis and ELSE keyword is required in an if...else.

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

(this is significant in your setting of "required_space" which has a trailing space which is included but that should have no effect on the if statement; just a matter of which to be aware)

Note that you are approaching the limit of batch's numeric range -2147483648..2147483647. If either value compared exceeds this limit, you need to convert to alphabetic mode and pad your values with leading characters, eg

 set "padded_var=                                     %var%"
 set "padded_var=%padded_var:~-25%"

the padding character ( here) is not paicularly significant, is commponly 0 (but then may need a non-numeric included to ensure it isn't interpreted as octal) if separators like spaces are use then "quote the arguments". The idea is to make the two values to be compared the same length so that the character-by-character left-to-right comparison proceeds as expected. Space is the "universal choice" since it sorts least of the normal characters.

Upvotes: 4

Related Questions