1

I see that this operator is used in windows (and might be Linux?) to chain/combine multiple commands in one line. Commands are executed one after another, as long as preceding complete successfully (exit code 0).

However, I do not understand if it can be used in batch file, where you specify commands one after another, one command per line. How do you achieve the same effect in this case? How do you split cmd1 && cmd2 && cmd3 into multiple lines? How do you terminate

cmd1
cmd2
cmd3

as soon as first command fails?

I would also like to know the name of the operator to find the answer to questions like this myself later.

1
cmd1 && cmd2 && cmd3

can be written in multiple lines as

cmd1
if not errorlevel 1 cmd2
if not errorlevel 1 cmd3

where each command execution will depend on the result of the previous one

5

In GNU/Linux I can split the command cmd1 && cmd2 && cmd3 into multiple lines in (e.g. for readability) in a script file like this:

cmd1 &&
cmd2 &&
cmd3
1
  • Useful it works even from the bash command-line (tested from 4.3.11(1)-release (x86_64-pc-linux-gnu) of 2013)... – Hastur Jul 12 '19 at 12:51
0

The difference between them is:

cmd1
cmd2
cmd3

will fire each command individually and allows for the termination of the batch job if you hit Ctrl + c before one finishes.

Where as

cmd1 && cmd2 && cmd3

will launch the commands one after the other, but, without looking at the script/in one go.

For further example,

Take the first example, if you edit the script whilst cmd1 is running and change cmd2 to cmd3, it will load cmd3 when cmd1 has finished.

On Linux, if I do ifdown eth0 I will lose my ssh session, so, instead I do ifdown eth0 && ifup eth0 to chain the commands.

If you want to do something with regards to fails, you should look at if statements and switches along with return codes and errorlevels. Linky .

0

How does && work?

However, I do not understand if it can be used in batch file, where you specify commands one after another, one command per line

The rest of this answer is for Windows batch files.


How do you split cmd1 && cmd2 && cmd3 into multiple lines?

The commands can be split using if and %errorlevel%

Setlocal EnableDelayedExpansion
cmd1
if !ERRORLEVEL! equ 0 (
  cmd2
  if !ERRORLEVEL! equ 0 (
    cmd3
    )
  )

I would also like to know the name of the operator &&

The && operator is one of two Conditional Operators. The other is ||.

commandA && commandB Run commandA, if it succeeds then run commandB

commandA || commandB Run commandA, if it fails then run commandB

Source Redirection


Further Reading

2
  • The inner tests will fail unless you use delayed expansion – dbenham Mar 17 '15 at 20:20
  • Good catch. Answer updated. – DavidPostill Mar 17 '15 at 21:41

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.