Search code examples
windowsbatch-filecmddosexit

bat does not return right exit status


I have two bat files. callexcode.cmd calls excode.cmd which just makes a call to file 'saurabh' which does not exist. When I want to get the error code printed in the caller (in this case callexcode.cmd, i get 0 which states that it is success. But the error code is 1 since there is no file called 'saurabh'. I am printing exit codes in both bat files. The callie displays the exit code to be 1 whereas the caller displays exit code to be 0. Could anyone please have a look and let me know where I am going wrong. Rather is there any reason the exit code is messed up.

callExcode.cmd

 IF "%1"=="abc" (
  SET good=%2
 )
 IF /I "%good%" == "pqr" ( 
 CALL exCode
 echo ' in file callexcode, error level ret = %ERRORLEVEL%'
 @EXIT /B %ERRORLEVEL% 
 )

excode.cmd

CALL saurabh 
echo 'in file excode'
echo 'exit code %ERRORLEVEL%'
@EXIT /B %ERRORLEVEL% 

output C:\docs>callExcode.cmd abc pqr

C:\docs>IF "abc" == "abc" (SET good=pqr )

C:\docs>IF /I "pqr" == "pqr" ( CALL exCode echo ' in file callexcode, error level ret = 0'

)

C:\docs>CALL saurabh 'saurabh' is not recognized as an internal or external command, operable program or batch file.

C:\docs>echo 'in file excode' 'in file excode'

C:\docs>echo 'exit code 1' 'exit code 1' ' in file callexcode, error level ret = 0'

Thanks in advance!

Saurabh


Solution

  • When you have code in ( ), the interpreter considers this a single line of code. Environment variables are expanded when the line is parsed, not when it is executed. You can work around this by using this line of code at the top of your script:

    setlocal enableextensions enabledelayedexpansion
    

    once you have that line, you can use

    !ERRORLEVEL!
    

    instead of

    %ERRORLEVEL%
    

    The ! instead of % to name environment variable names means "expand this variable when the line of code is executed, not when it is parsed."

    Bill