Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected double ampersand/pipe behavior when chaining batch script

Tags:

batch-file

cmd

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?

like image 574
Kevin Avatar asked Aug 15 '19 20:08

Kevin


1 Answers

|| 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.

like image 64
dbenham Avatar answered Oct 21 '22 06:10

dbenham