Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a parameter (or variable) is a number in a Batch script

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
like image 315
mhshams Avatar asked Jul 11 '13 02:07

mhshams


People also ask

What does %% mean in batch script?

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> )

What is == in batch?

[ == ] (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.

Can batch file take parameters?

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.


3 Answers

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

like image 91
Magoo Avatar answered Oct 07 '22 15:10

Magoo


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
like image 22
Endoro Avatar answered Oct 07 '22 15:10

Endoro


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.)

like image 25
hornzach Avatar answered Oct 07 '22 16:10

hornzach