I am looking to create a batch file that, when ran, creates a random integer from 0 to 100 and then runs it through an if statement that checks whether it is odd or even. I\'ve
@ECHO OFF
SETLOCAL
set /a num=%random% %%100 +1
SET /a nummod2=num %% 2
IF %nummod2% == 0 (ECHO %num% is even) ELSE (ECHO %num% is odd)
GOTO :EOF
Conventional IF
syntax is if [not] operand1==operand2 somethingtodo
where operand1 and operand2 are both strings. If the strings contain separators like Space,Tab or other characters that have a special meaning to batch then the string must be "enclosed in quotes"
.
Fundamentally, if
compares strings. The operator must be one of a fixed set of operators [== equ neq gtr geq lss leq] hence cmd
was objecting to num
where it expected an operator.
A calculation cannot be performed within a if
statement's parameters.
%%
is required to perform the mod
operation, since %
is a special character that itself needs to be escaped by a %
.
Note that {
and }
are ordinary characters with no special meaning to batch and remarks must follow
rem remark string
There is a commonly-used exploit which is
::comment
actually, a broken label, which can have unforeseen side-effects (like ending a code-block)