Reputation: 24007
The following Windows batch file called "foo.bat" echos "quitting" and sets the return code to 1 as I expect:
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
)
But, to my surprise, the return code of this batch file is 0:
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
echo anything
)
I determine the batch file's return code like so in the Windows command prompt:
> cmd.exe /c foo.bat
quitting
> echo %ERRORLEVEL%
0
I've verified that ERRORLEVEL is not already set in my environment, running set ERRORLEVEL
prints "Environment variable ERRORLEVEL not defined" as expected.
Everything else about the second file works as expected. It does echo "quitting" and does not echo "anything". It appears that adding the echo anything
line to the script means that the line exit /B 1
still exits but does not set the return code.
This is Windows 7 in EC2. ver
reports "Microsoft Windows [Version 6.1.7601]".
Is there a way to ensure exit /B 1
really sets the return code, even in complex if statements?
Upvotes: 2
Views: 1693
Reputation: 69
I had the same trouble. I solved it with something like this:
if "1"=="1" (
if "1"=="1" (
echo quitting
goto Exit1
)
echo anything
)
goto :Eof
:Exit1
exit /b 1
Another "known" defect is this:
rem t.bat
copy non-existing somewhere
rem
C:\> cmd /c t.bat
The system cannot find the file specified.
C:\> echo %errorlevel%
0
Explicit returning of errorlevel at end of batch file does not work when run with cmd /c if there is a comment after (or echo or something that is supposed to not normally change the errorlevel). So need to use this instead:
rem t.bat
copy non-existing somewhere
exit /b %errorlevel%
rem
C:\> cmd /c t.bat
The system cannot find the file specified.
C:\> echo %errorlevel%
1
Upvotes: 0
Reputation: 24007
If I change the file extension from ".bat" to ".cmd", then it behaves as expected.
Upvotes: 2
Reputation:
What is your test environment? Are you shure therE are no other side effects involved?
This batch got the expected results in Win7Ult and Win10pro
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
ver > nul
Call :First
Echo called First ErrorLevel = %Errorlevel%
ver > nul
Call :Second
Echo called Second ErrorLevel = %Errorlevel%
Pause
Goto:Eof
:First
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
)
Goto :EoF
:Second
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
echo anything
)
quitting
called First ErrorLevel = 1
quitting
called Second ErrorLevel = 1
Upvotes: 0