Exit / b does not work correctly when inside a block with other commands

I have a batch file that needs to be run in a 32-bit context, so it contains a bit of code to call a 32-bit shell with its own path. This script should also be able to return an error code if it crashes through exit /b 123. However ...
When it exitis in a block ( ), AND contains any statement after it, it does not return correctly.

@echo off
setlocal EnableDelayedExpansion

rem Ensure we're running in 32-bit mode
if not %PROCESSOR_ARCHITECTURE%==x86 (
  echo Thunking to 32-bit mode
  %Windir%\SysWOW64\cmd.exe /c %0
  echo !ERRORLEVEL!
  exit /b !ERRORLEVEL!
)

(
  echo before
  exit /b 456
  echo after
)

The output is as follows:

H:\>sub.bat
Thunking to 32-bit mode
before
0

H:\>

If you delete echoafter exit, then it will work exactly as expected.

H:\>sub.bat
Thunking to 32-bit mode
before
456

H:\>

echo rem , . 32- cmd.exe script, .

H:\>sub.bat
before

H:\>echo %ERRORLEVEL%
456

H:\>

- ?

+4
1

/b "else" script , cmd.exe.

Syswow64, 456. cmd.exe , . Cmd.exe , , 0, .

/b "else" script, cmd.exe, . cmd.exe 456, .

"exit" , , !

+5

Source: https://habr.com/ru/post/1619522/


All Articles