Exiting batch with `EXIT /B X` where X>=1 acts as if command completed successfully when using && or || operators between batch calls

孤人 提交于 2019-11-28 07:33:36

If you ask me, exit codes in batch files are broken for this exact reason, but there is a hacky workaround you can use. As the last line of your batch file, use:

@%COMSPEC% /C exit 1 >nul

Since this is an actual process that is started you get a real process exit code and && and || will work.

It works as it should when using call to execute batch scripts containing an exit statement:

C:\>echo @EXIT /B 1 > a.bat

C:\>call a.bat && echo yes

C:\>call a.bat || echo yes
yes

By the way, it says wrongly on Microsoft docs:

Call has no effect at the command prompt when it is used outside of a script or batch file.

user2989311

If you use start /wait you can also use this in a very simple Windows application (written in C#) called by DOS batch files like so:

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Environment.ExitCode = Convert.ToInt32(args[0]);
    }
}

Then the application can be called by your DOS batch file and evaluate the result. i.e.

c:> start /wait SetRC 1
c:> if "%errorlevel%"=="1" goto abort

NOTE: the /wait is not necessary in a batch file.

You could pass in the return code you want as an argument to your program.cs and get it out this way guaranteed.

TheDude

I think you are getting Errorlevel=0 with because you are indeed executing a.bat (regardless of the return code).

You would fail the check if a.bat did not exist. CALL is the only way I know to pull in the environment from a.bat.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!