0

I have 2 separate sets of batch commands that are run independently in separate files. I figured out how to create a single batch file to execute both using the following:

CALL %0\..\"MyBatchFile.bat"

if errorlevel 0 ( 
    REM do some additional commands here
)

This actually works perfectly and then I only have to run 1 batch file to execute everything. However it still requires 2 separate batch files. What I want to do is replace that call to the external batch file and have the calls from that file directly in a single batch file.

Issue is I can't figure out the syntax to essentially behave the same but with only a single file:

Execute the 2nd set of statements, only after the 1st set has finished without error.

I tried using the && operator between sets of statements but it didn't execute both sets of statements. Any idea how to have all statements within a single file and only execute the 2nd set after the 1st set has finished successfully?

atconway
  • 20,624
  • 30
  • 159
  • 229

1 Answers1

1

First off, your code in your question is not correct. If you want to call another script that resides in the same folder as your currently running script, then you should use %~dp0 to get the drive and path, with trailing \, but without the actual script file name:

call "%~dp0MyBatchFile.bat"

You could use "%~f0\..\MyBatchFile.bat" instead, but "%~dp0MyBatchFile.bat%" is more direct and easier to understand. It is important to include quotes around the entire construct, just in case the path includes spaces or poison characters.

Also, your IF condition is wrong - IF ERRORLEVEL 0 ... runs if ERRORLEVEL is greater than or equal to 0, which is pretty much always (unless your command returns a negative ERRORLEVEL).

You want IF %ERRORLEVEL%==0 .... Or you could use IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 ...

If you know that your ERRORLEVEL can never be negative, then you could use IF NOT ERRORLEVEL 1.

For an extensive discussion of error detection possibilities, see Foolproof way to check for nonzero (error) return code in windows batch file


As for your actual question...

I'm not sure I understand, but I believe all you need to do is CALL a :label within your script instead of an external file.

@echo off
call :someLabel
if %errorlevel% equ 0 (
  REM do some additional commands here
)
exit /b

:someLabel
REM commands from MyBatch.bat go here

It might be cleaner to EXIT /B upon error instead of using parentheses.

@echo off
call :someLabel
if %errorlevel% neq 0 exit /b
REM do some additional commands here
exit /b

:someLabel
REM commands from MyBatch.bat go here
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390