Bash/sh - difference between && and ;

69,857

Solution 1

If previous command failed with ; the second one will run.

But with && the second one will not run.

This is a "lazy" logical "AND" operand between operations.

Solution 2

I'm using && because a long time ago at the nearby computer:

root# pwd
/
root# cd /tnp/test; rm -rf *
cd: /tnp/test: No such file or directory
...
... and after a while ...
...   
^C

but not helped... ;)

cd /tnp/test && rm -rf * is safe... ;)

Solution 3

In cmd1 && cmd2, cmd2 is only executed if cmd1 succeeds (returns 0).

In cmd1 ; cmd2, cmd2 is executed in any case.

Both constructs are part of a POSIX-compliant shell.

Solution 4

&& means to execute next command if the previous exited with status 0. For the opposite, use || i.e. to be executed if previous command exits with a status not equal to 0 ; executes always.

Very useful when you need to take a particular action depending on if the previous command finished OK or not.

Solution 5

Commands separate by ; are executed sequentially regardless of their completion status.

With &&, the second command is executed only if the first completes successfully (returns exit status of 0).

This is covered in the bash manpage under Lists. I would expect any Unix-like shell to support both of these operators, but I don't know specifically about the Android shell.

Share:
69,857

Related videos on Youtube

psihodelia
Author by

psihodelia

Software Engineer

Updated on May 31, 2020

Comments

  • psihodelia
    psihodelia about 4 years

    I normally use ; to combine more than one command in a line, but some people prefer &&. Is there any difference? For example, cd ~; cd - and cd ~ && cd - seems to make the same thing. What version is more portable, e.g. will be supported by a bash-subset like Android's shell or so?

  • glenn jackman
    glenn jackman about 13 years
    Here's a link to the bash manual: gnu.org/software/bash/manual/bashref.html#Lists
  • melvynkim
    melvynkim about 10 years
    To be safer, I'd use rm -rf /tnp/test
  • radrow
    radrow almost 6 years
    To be even safer it is better to use rm /tnp/test/ -rf to prevent deadly enter missclick
  • Peter Chaula
    Peter Chaula almost 6 years
    In other words it's got a short-circuit behaviour
  • Shayan
    Shayan almost 5 years
    @peter Which one? The ; one or the && one? Or do you mean both?
  • Peter Chaula
    Peter Chaula almost 5 years
    @Shayan, the &&.
  • Vthechamp
    Vthechamp over 3 years
    So you would prefer to run sudo apt update && sudo apt upgrade and not sudo apt update; sudo apt upgrade, right?
  • Scott H
    Scott H over 2 years
    Note that if you combine && and ||, then you must put the && first. Otherwise, the && executes if either the original or the || command succeeds (exits with 0 status).