Alan
Alan

Reputation: 37

Difference between "call: exit, echo" and "exit, echo" in batch file

I've run into something confusing about the following batch code:

@echo off
Setlocal EnableDelayedExpansion

set rootpath=%1

if '%1'=='' (
call :ERR
REM Exit /b 1001
) else (
exit /b 0
)
echo %errorlevel%
goto :EOF

:ERR
Exit /b 1001

and

@echo off
Setlocal EnableDelayedExpansion

set rootpath=%1

if '%1'=='' (
REM call :ERR
Exit /b 1001
) else (
exit /b 0
)
echo %errorlevel%
goto :EOF

:ERR
Exit /b 1001

The only difference is that the first one uses call but the second one does not. Also, "echo" does not work on the second one. Can anyone help me understand these issues?

Upvotes: 1

Views: 800

Answers (1)

Magoo
Magoo

Reputation: 79982

exit /b n does two things. It sets errorlevel to n and then it returns to the next instruction in the routine that called the current routine.

So in the first - call :err sets errorlevel and returns to the echo which shows errorlevel as set, then proceeds to :EOF terminating the main routine.

or

terminates the main routine, having set errorlevel to 0

(depending on the if being true/false.)

In the second, the routine is terminated by the exit having set errorlevel to 1001 or 0 (depending on the if being true/false) and hence processing never reaches the echo.

Upvotes: 1

Related Questions