Home > Enterprise >  Operator IF doesnt check condition of values in cmd
Operator IF doesnt check condition of values in cmd

Time:07-25

Hi everyone I writing little .bat file and seemed for I was ended but I got error. Operator IF does not checking Permission value and Free space conditions of values and are not compering. All the time I get "false" even when the free space on disc D is less then 25Gb (26,843,545,600 bits) My code looks such:

@echo off
@setlocal enableextensions enabledelayedexpansion

set permissiblevalue=26,843,545,600
set permissiblevalue=%permissiblevalue:,=%

for /f "tokens=3" %%a in ('dir d:\') do (
    set bytesfree=%%a
)

set bytesfree=%bytesfree:,=%

if %permissiblevalue% leq %bytesfree% (
    The disk D is checking.....
) else (
    echo msgbox "Lacks of free space on disk D. Klick OK for delete files!!!" > %tmp%\tmp.vbs
    wscript %tmp%\tmp.vbs
    del %tmp%\tmp.vbs
    %SystemRoot%\explorer.exe "d:\"
)

exit

Please explain to me Where is the mistake

CodePudding user response:

If the two arguments to if are both pure numeric strings, cmd will convert them to integers and compare them as integers. BUT cmd is limited to 2^31 and mechanically processes the string character-by-character, left-to-right, multiplying by 10 and adding the next value, so any value greater than 2147483647 will be processed incorrectly (but won't generate en error).

Consequently, if you are using large numbers, you need to force cmd to interpret them as strings. This is easily done by "quoting each string". BUT a string comparison is performed character-by-character, so you need to leading-0-fill each so that they are the same length.

To do this :

set "zeroes=000000000000000000000000000000000000000000000000000000000"
set "var=%zeroes%%var%"
set "var=%var:~-20%"

Which prepends a series of 0 characters to the current value of var, then sets var to the last 20 characters of the result.

You can then safely use if "%var%" leq "%someothervar%"

Tip : Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier.

  • Related