Home > Enterprise >  exit /b not working properly inside block with further statements
exit /b not working properly inside block with further statements

Time:11-15

I'm working on a problem in a codebase where a perl script calls a batch script and does stuff based on the exit code. In some cases, although statements like exit /b 1 are executed and the batch script exits, the exitcode is seen as 0 by the perl script. I've narrowed it down to the following example.

Here's a minimal version of the perl script:

#!/usr/bin/perl
print "calling bat with @ARGV\n";
qx(batscript.bat @ARGV);
my $exitcode = $? >> 8;
print "return code from bat is $exitcode \n";

And here's a minimal version of the batch script:

@echo OFF
setlocal enableextensions
if "%~1" == "err" (
    echo "non-zero code requested"
    exit /b 1
    echo hello
)
endlocal

This is what I get:

c:\tmp>plscript.pl
calling bat with
return code from bat is 0

c:\tmp>plscript.pl err
calling bat with err
return code from bat is 0

If I remove that echo hello line from the batch script, it works properly:

c:\tmp>plscript.pl
calling bat with
return code from bat is 0

c:\tmp>plscript.pl err
calling bat with err
return code from bat is 1

Is this a bug in how batch runs and processes statements in blocks? It would be preferable not to have to refactor the batch script since it's quite big and has many exit /b statements.

CodePudding user response:

Based on a suggestion from aschipfl, I eventually settled on changing the way the batch script is called, by using CALL. I like this solution because I don't have to modify the batch script (which can be called either by the perl script or by users directly from a cmd.exe window).

So basically in the perl script I changed the 3rd line from:

qx(batscript.bat @ARGV);

to:

qx(call batscript.bat @ARGV);
  • Related