Command Line Parameters In Nested IF Statements
Posted on 2009-04-28
The problem here is simple. The code is written lexically correct. The nested IF statements are logically correct. Before the interpreter attempts to run this code, it first tries to resolve variables including command line variables. Where comparisons are made against %2, for the program to reach that part of the code %2 would infact be defined but the interpreter appears to ignore this logical fact. Is there a way to force the interpreter to accept this code without detracting from the current style?
What the code does: Simply put, it generates a random number between a min value and a max value. If there are no parameters, min and max are set to 1 and 9 respectively. If two values are passed as parameters then min and max are set to %1 and %2. Tests are then performed to validate that %1 and %2 are in range as well as the order of %1 and %2. Really simple but an annoyingly frustrating oversight.
if "%1"=="" (
set /a Min = 1 // There are no parameters so set default values
set /a Max = 9
) else (
if not "%2"=="" ( // %1 exists....
if /i %1 lss 1 exit /b -2 // %2 also exists so validate both %1 and %2....
if /i %1 gtr 9 exit /b -3
if /i %2 lss 1 exit /b -4
if /i %2 gtr 9 exit /b -5
if /i %1 gtr %2 exit /b -6
set /a Min = %1 // and if all is well, set min and max values
set /a Max = %2
) else (
exit /b -1 // %1 exists but %2 does not so no need to validate either
) // The rest of the code os okay
set /a num = %random% %% (%max% - %Min% + 1) + %Min%
echo %num% // This line will be removed after debugging is complete
exit /b %num%