45

I have a .bat file in windows that does three things

cmd1 arg1 arg2
cmd2 arg3 
cmd3 arg4 arg5 arg6

Sometimes cmd1 can fail and that's fine, I would like to carry on and execute cmd2 and cmd3. But my bat stops at cmd1. How can I avoid this?

Update for clarity - these are not other .bat files, they are exe commands. Hopefully I don't have to build a tree of .bat files just to achieve this.

2
  • You should be able to start the command using cmd /C. Jan 3, 2013 at 22:49
  • 1
    You need to show a specific code example of what is not working. Batch files normally do not terminate automatically if a command fails with an error. Batch files do terminate if there is a syntax error. If your code is exiting upon an exe error, then there must be logic in your code that is causing that behavior.
    – dbenham
    Jan 4, 2013 at 14:59

3 Answers 3

33

Another option is to use the amperstand (&)

cmd1 & cmd2 & cmd3

If you use a double, it only carries on if the previous command completes successfully (%ERRORLEVEL%==0)

cmd1 && cmd2 && cmd3

If you use a double pipe (||), it only runs the next command if the previous completes with an error code (%ERRORLEVEL% NEQ 0)

cmd1 || cmd2 || cmd3

10
  • Can I do this when passing args also? I just tried and it didn't see to work. Jan 3, 2013 at 22:39
  • @ConfusedNoob I do all the time... I have a CHKDSK command, with arguments, that works. I type check D: & check E: & check F:, and it works. The arguments the BAT file has include the /perf /f /r /b /scan switches Jan 3, 2013 at 23:14
  • 2
    good one! brought me an idea how to implement several retries: cmd || cmd || ... will execute next cmd until succeeds
    – iTake
    Nov 11, 2013 at 17:21
  • 2
    This makes long scripts unreadable, is there no other way?
    – jan
    Oct 10, 2014 at 7:53
  • 1
    @CanadianLuke Well batch is the windows batch framework. How do you run hundreds of commands non interactively? Is there a better approach in the power shell? Is that worse to move there?
    – jan
    Oct 13, 2014 at 13:54
19

This worked for me:

cmd.exe /c cmd1 arg1
cmd2
...

This uses cmd.exe to execute the command in a new instance of the Windows command interpreter, so a failed command doesn't interrupt the batch script. The /c flag tells the interpreter to terminate as soon as the command finishes executing.

cmd2 executes even if the first command fails. See cmd /? from Windows Command Prompt for more information.

17

Presumming the cmds are other .bat files stack the commands like this:

 call cmd1
 call cmd2
 call cmd3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.