windowsif-statementbatch-filecmdvariable-assignment

Batch file argument that may be passed as integer


I try to write a batch script comparing the input with 2 integers and if it's in their range, the value is assigned to a variable. The other string parameters can be also passed as an argument so I don't know which argument is the one I'm looking for.

I'm trying sth like this:

SET MIN=20
SET MAX=79
if not "%~1"=="" (
    if %2 leq %MAX% if %2 geq %MIN% set VAR=%2
    )
if not "%~2"=="" (
    if %2 leq %MAX% if %2 geq %MIN% set VAR=%2
    )
if not "%~3"=="" (
    if %3 leq %MAX% if %3 geq %MIN% set VAR=%3
    )

The problem is when I pass only 2 arguments to the script the 3rd condition will crash with a message:

79 was unexpected at this time.

It looks like the expression inside the condition is evaluated by the script and I'm not sure how I can solve this.

Sth like this works but I don't like it because it looks terrible:

if not "%~2"=="" (set TMP_VAR=%2) else (set TMP_VAR=99999)  
if %TMP_VAR% leq %MAX% if %TMP_VAR% geq %MIN% set VAR=%TMP_VAR%

Solution

  • If you can guarantee a maximum of only one argument in range, (and you aren't passing crazy arguments), then you can probably just do it like this:

    For %%G In (%*) Do If 1%%~G GEq 1%MIN% If 1%%~G LEq 1%MAX% Set "VAR=%%~G"
    

    This idea utilises %*, which represents all arguments. The For loop passes each argument one at a time through to the Do portion which performs the range comparison on them, and defines the VAR variable with the content of the last comparison match.