Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 2 numbers in DOS Batch Not Working

I'm an old-timer who is a newbie to DOS Batch programming. I have what I think is a very simple batch script, that is not working. I looked for similar posts, and didn't find one that matched.

I am running the below script on XP. My goal is to check for free disk space before proceeding further, but I ran into a problem comparing 2 numbers, so the below script contains only that logic. I have hard-coded numbers to show the problem, which is... The comparison (if x gtr y) seems not to work, and so the branch logic goes to the wrong place. Either that, or I'm messing up somewhere else in the IF statement. (Some of the echo statements are unnecessary - they are for debugging - but I left them in for now.)

Any enlightenment on where I'm going wrong would be GREATLY appreciated.

Thx...

@echo off

set Free=217522712576
set Need=20000000000

echo Free=%Free%
echo Need=%Need%

echo on
IF %Free% GTR %Need% (GOTO Sufficient_Space) ELSE GOTO Insufficient_Space
@echo off

:Insufficient_Space
@ECHO INSUFFICIENT SPACE
GOTO DONE

:Sufficient_Space
@ECHO SUFFICIENT SPACE

:DONE
like image 487
feenyman99 Avatar asked Oct 14 '11 15:10

feenyman99


3 Answers

Those numbers would overflow a 32 bit integer so guessing your on a 32 bit version of windows, that's why its failing.

C:\>set /a test=1+2
3

C:\>set /a test=1+217522712576
Invalid number.  Numbers are limited to 32-bits of precision.
like image 76
Alex K. Avatar answered Nov 05 '22 16:11

Alex K.


As others said the numbers are too big, however if you keep them as strings and pad out to be the same length, it looks to work

@echo off

rem cant do this get: Invalid number.  Numbers are limited to 32-bits of precision.
set Free=217522712576
set Need=2000000000

rem can do 
set Free=00000000000%Free%X
set free=%Free:~-13%

set Need=00000000000%Need%X
set Need=%Need:~-13%


echo Free=%Free%
echo Need=%Need%

echo on
IF %Free% GTR %Need% (GOTO Sufficient_Space) ELSE GOTO Insufficient_Space
@echo off

:Insufficient_Space
@ECHO INSUFFICIENT SPACE
GOTO DONE

:Sufficient_Space
@ECHO SUFFICIENT SPACE

:DONE
like image 26
Andy Morris Avatar answered Nov 05 '22 16:11

Andy Morris


Note That CMD Had A precision betweeb -2^31 to 2^31-1 that equal to -2 147 483 648 to 2 147 483 647 If smaller of bigger than the limit a warning came:Invalid number. Numbers are limited to 32-bits of precision.

like image 27
GaryNg Avatar answered Nov 05 '22 17:11

GaryNg