user1995781
user1995781

Reputation: 19453

Windows batch choice option

I have a windows batch file that look like this:

choice /C:123 /n /m "Generate output? (1. Debug only 2. Production only 3. Both debug and production)"
if errorlevel==1 (
    echo 1
)
if errorlevel==2 (
    echo 2
)
if errorlevel==3 (
    echo 3
)

The problem is when user select 3, it will echo out 1, 2 and 3. Which it should only echo 3. How can I solve it?

Upvotes: 1

Views: 516

Answers (1)

npocmaka
npocmaka

Reputation: 57252

The solution is in the SomethingDark's comment. The reason why your script fails is because = is a standard delimiter in batch files (like <space><tab>;,) and your conditions take other form of IF command different than comparison:

IF ERRORLEVEL N execute command

Which means - if errorlevel is equal or bigger than N execute the command.So that's why with 3 all conditions are performed.

And for real equality check you need:

choice /C:123 /n /m "Generate output? (1. Debug only 2. Production only 3. Both debug and production)"
if %errorlevel% EQU 1 (
    echo 1
)
if %errorlevel% EQU 2 (
    echo 2
)
if %errorlevel% EQU 3 (
    echo 3
)

Mind that == always forces a string comparison and EQU, NEQ, LSS, LEQ, GTR, GEQ are the correct switches for numeric comparison (which is not so crucial when you perform equality check )

Upvotes: 3

Related Questions