32

How do we combine commands in cmd shell language such that the second command is only executed if the first command successfully completed?

something like following bash-command

make && ./a.out

a.out is only executed if make was successful

magikarp
  • 460
  • 1
  • 8
  • 22
user674669
  • 10,681
  • 15
  • 72
  • 105

2 Answers2

57

The following

command1 && command2

should work on cmd as well. Quote from here:

When using cmd.exe, you can put multiple commands on the same line by using ‘&’ or ‘&&’ between commands. Using a single ampersand (&) will cause the first command and then the second command to be run in sequence. Using double ampersands (&&) introduces error checking. The second command will run only if the first command is successful.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 6
    Is there any way to break run multiple commands on **different** lines? A whole long script with error checking all the way through it looks terrible on a single line. – brittohalloran Aug 03 '12 at 11:56
  • as ABCD.ca said below. add "\" at the end of the line. This escapes the newline character. "command \" then on another line, "&& conditional_command" – xy0 Nov 09 '18 at 21:47
23

An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • 6
    if your command1 is long then you can escape the end of the line that contains command1 with a trailing backslash: `verylongcommand1 \ `. Then on line 2 you can have ` && command2 ` – ABCD.ca Oct 06 '15 at 00:49
  • @ABCD.ca Maybe you can escape your newline characters? – mazz0 Aug 16 '16 at 08:01