2

According to my code, If %~1 is greater than 7000, go to ExceedError

IF "%~1" GTR "7000" GOTO ExceedError

Contents of ExceedError:

ECHO Value exceeded the maximum value. See help file.
EXIT /B

But this happened:

...modules>If "71" GTR "7000" GOTO ExceedError

...modules>Echo Value exceeded the maximum value. See help file.
Value exceeded the maximum value. See help file.

...modules>exit /B

What happened? Is there something wrong?

amegyoushi
  • 524
  • 4
  • 14

1 Answers1

6

you've enclosed arguments with double quotes and this forces a string comparison. To compare numbers try without the quotes:

IF %~1 GTR 7000 GOTO ExceedError

In case you want to prevent errors you can add one more line:

set /a "_number=%~1" >nul 2>&1 || set "_number=0"
IF %_number% GTR 7000 GOTO ExceedError

In case of wrong input you'll compare the values with a 0 as default value. You can change it if you need

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • Oh, I didn't know that! Thank you for solving the problem! But what if they typed symbols on `%~1`, for example `>EE#`. It contains the illegal character `>`. So the script would interpret it wrong, and do something different. My goal is "unless it's a number, `GOTO ExceedError`". Is there a way to do that? – amegyoushi Oct 30 '18 at 08:30
  • 2
    @scriptmastere02 That’s a separate question. Please check [how to check if a parameter (or variable) is numeric in windows batch file](https://stackoverflow.com/q/17584282/711006), for example. – Melebius Oct 30 '18 at 08:50
  • @Melebius It won't change the problem of accepting illegal characters. – amegyoushi Oct 30 '18 at 10:15
  • 1
    This method to test for valid numbers is not reliable. There are a ton of inputs that will not cause an error, like `!-~123` or the _name_ of any variable, like `AA123`. If the variable is not defined or contains an invalid number, the result is zero with no error. If the variable contains a valid number the result is such a number; this could lead to strange errors... – Aacini Oct 30 '18 at 13:55