Amine Kchouk
Amine Kchouk

Reputation: 172

Arithmetics in IF statement (Batch)

I am currently learning how to program in batch, but I have encountered a problem. I tried to run this script but somehow it isn't working:

set /a x=5
if %x%+1 equ 6 (@echo x + 1 is equal to 6)
echo [%x%+1]
echo.
pause

This is what it prints:

[5+1]

Press a key to continue...

Basically I just want to know how to do arithmetics in an if statement.

Upvotes: 3

Views: 4585

Answers (1)

JosefZ
JosefZ

Reputation: 30133

The == comparison operator always results in a string comparison. IF command will only parse numbers when one of EQU, NEQ, LSS, LEQ, GTR, GEQ comparison operator is used. A non-numeric character in any of compared values leads to a string comparison as well.

Arithmetic expressions are allowed in SET /a commands only. You could use

set /a "x=5"
set /a "y=x+1"
if %y% equ 6 (@echo x + 1 is equal to 6)
echo [%x%+1]=%y%
echo.
pause

Upvotes: 3

Related Questions