mardi 7 juillet 2020

Batch if/else if executes both branches

The following code seems to execute both branches of if and i can't fathom why.

@ECHO OFF

set _ERROR=500

If %_ERROR%==500 goto :FIRST
If NOT %_ERROR%==0 If NOT %_ERROR%==500 goto :SECOND

:FIRST
echo FIRST Error code: %_ERROR%

:SECOND
echo SECOND Error code: %_ERROR%

EDIT

Only the first if branch was executed, but both echoes are printed due to batch running code line by line, goto being used for better structuring and line skipping not for isolating execution logic.

This is the working code:

@ECHO OFF

set _ERROR=500

If %_ERROR%==500 goto :FIRST
If NOT %_ERROR%==0 If NOT %_ERROR%==500 goto :SECOND

:FIRST
echo FIRST Error code: %_ERROR%
goto :END

:SECOND
echo SECOND Error code: %_ERROR%
goto :END

:END

Aucun commentaire:

Enregistrer un commentaire