1

I understand that in bash programming, comamnd1;command2;command3 will run them sequentially while command1&&command2&&command3 will run them in parallel. However what happens when I combine ; and && together, e.g. command1 ; command2 && command 3? What is precedence between ; and && in bash? Is above command equivalent to (command1;commmand2) && command3 or to (command1);(command2 && command3)

1
  • 1
    You are mistaken, && will not cause the commands to run in parallel. It will run them sequentially as ; with the difference that the seconds command will be executed only if the first one returns 0 exit status. This is called short-circuit evaluation. – pabouk Nov 11 '14 at 23:52
6

First thing: to run a command in the background you type it followed by a single & , the double && is a logical and operator (as well as || is logical or). Running command1 && command2 returns logical true (i.e. return code 0, which means "no error") if both commands return without error. As a much used side effect, command2 is not executed when command1 has returned an error, since the result of the logical and operation cannot yield true if the first argument is already known to be false.

command1 ; command2 & command3

Commands are executed left to right: first command1 is run, waited until it has finished, then command2 is run in the background (as it is followed by &) and immediately followed by command3.

You can use braces to let a sequence of commands be run in the background like this:

{ command1 ; command2 ; } & command3
2
  • 1
    Note: in your first command line, I believe you mean command2 to be the second entry. (I'd have done an edit, but they must be at least 6 characters, so...) – lindes-hw Nov 12 '14 at 18:59
  • 1
    You are right, thanks to mpy for correcting this. – ua2b Nov 13 '14 at 1:14

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.