My foo.bat file:
exit /b 1
What I execute in a cmd prompt:
foo.bat && echo "OK"
Result:
exit /b 1
"OK"
Yet, when I use double pipe, the echo doesn't occur:
foo.bat || echo "OK"
Result:
exit /b 1
This is the exact opposite behavior of what I expect && and || to do. See https://ss64.com/nt/call.html, where it says:
commandA && commandB Run commandA, if it succeeds then run commandB
and
commandA || commandB Run commandA, if it fails then run commandB
Am I losing my mind? What am I missing here?
||
and &&
respond to the return code of the previous command (the last executed command on the left). All programs exit with an error code, regardless of context.
EXIT /B 1
sets the batch ERRORLEVEL, which is strictly a cmd.exe concept.
The return code and ERRORLEVEL are not the same thing!
When a batch file is executed, the exiting ERRORLEVEL is only returned as the return code if the batch file was executed via CALL
.
When a batch file is executed without CALL, &&
and ||
respond to the last command executed within the script.
EXIT /B 1
sets ERRORLEVEL to 1, but the command executed successfully, so the return code is 0.
When CALL
is used, the CALL command looks at the ERRORLEVEL after the script terminates, and sets the return code to the ERRORLEVEL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With