07-23-2023, 11:00 AM
I'm facing a weird situation where a batch file I wrote reports an incorrect exit status. Here is a minimal sample that reproduces the problem:
### `bug.cmd`
echo before
if "" == "" (
echo first if
exit /b 1
if "" == "" (
echo second if
)
)
echo after
If I run this script (using Python but the problem actually occurs when launched in other ways too), here is what I get:
python -c "from subprocess import Popen as po; print 'exit status: %d' % po(['bug.cmd']).wait()"
echo before
before
if "" == "" (
echo first if
exit /b 1
if "" == "" (echo second if )
)
first if
exit status: 0
Note how `exit status` is reported as `0` even though `exit /b 1` should make it be `1`.
Now the weird thing is that if I remove the inside `if` clause (which should not matter because everything after `exit /b 1` should not be executed anyway) and try to launch it:
### `ok.cmd`
echo before
if "" == "" (
echo first if
exit /b 1
)
echo after
I launch it again:
python -c "from subprocess import Popen as po; print 'exit status: %d' % po(['ok.cmd']).wait()"
echo before
before
(environment) F:\pf\mm_3.0.1\RendezVous\Services\Matchmaking>if "" == "" (
echo first if
exit /b 1
)
first if
exit status: 1
Now the `exit status` is correctly reported as `1`.
I'm at loss understanding what is causing this. Is it illegal to nest `if` statements ?
**How can I signal correctly and reliably my script exit status in batch ?**
Note: calling `exit 1` (without the `/b`) is not an option as it kills the whole interpreter and prevents local script usage.
### `bug.cmd`
echo before
if "" == "" (
echo first if
exit /b 1
if "" == "" (
echo second if
)
)
echo after
If I run this script (using Python but the problem actually occurs when launched in other ways too), here is what I get:
python -c "from subprocess import Popen as po; print 'exit status: %d' % po(['bug.cmd']).wait()"
echo before
before
if "" == "" (
echo first if
exit /b 1
if "" == "" (echo second if )
)
first if
exit status: 0
Note how `exit status` is reported as `0` even though `exit /b 1` should make it be `1`.
Now the weird thing is that if I remove the inside `if` clause (which should not matter because everything after `exit /b 1` should not be executed anyway) and try to launch it:
### `ok.cmd`
echo before
if "" == "" (
echo first if
exit /b 1
)
echo after
I launch it again:
python -c "from subprocess import Popen as po; print 'exit status: %d' % po(['ok.cmd']).wait()"
echo before
before
(environment) F:\pf\mm_3.0.1\RendezVous\Services\Matchmaking>if "" == "" (
echo first if
exit /b 1
)
first if
exit status: 1
Now the `exit status` is correctly reported as `1`.
I'm at loss understanding what is causing this. Is it illegal to nest `if` statements ?
**How can I signal correctly and reliably my script exit status in batch ?**
Note: calling `exit 1` (without the `/b`) is not an option as it kills the whole interpreter and prevents local script usage.