I need to check if a parameter that is passed to a Windows Batch file is a numeric value or not. It would be good for the check to also works for variables.
I found an answer to a similar question, where the findstr
command is used with a regular expression.
I did try that solution, but it’s not working like I hoped (at least on Windows 7).
My test scenarios are as follows:
AA # not a valid number
A1 # not a valid number
1A # not a valid number
11 # a valid number
Represents a replaceable parameter. Use a single percent sign ( % ) to carry out the for command at the command prompt. Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> )
[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.
Batch parameters (Command line parameters): In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on. If you require all arguments, then you can simply use %* in a batch script.
SET "var="&for /f "delims=0123456789" %%i in ("%1") do set var=%%i
if defined var (echo %1 NOT numeric) else (echo %1 numeric)
Replace %1
with %yourvarname%
as appropriate
for ± integers
(test also for leading zero):
echo(%~1|findstr "^[-][1-9][0-9]*$ ^[1-9][0-9]*$ ^0$">nul&&echo numeric||echo not numeric
You could try this. The variable passed is for example var
and %var%
is equal to 500
.
set /a varCheck=%var%
if %varCheck% == %var% (goto :confirmed) else (exit /B)
exit /B
:confirmed
:: You can use %var% here, and it should only be executed if it is numerical!
if %var%
is equal to e.g. a3453d
, then it would set varCheck
to be 0
, and because 0
is not equal to a3453d
, then it will exit batch processing.
(The exit on line 3 is just in case the if statement decides not to execute for some reason ... XD.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With