Bash / sh - the difference between && and;

I usually use ; to combine multiple commands into a string, but some prefer && . Is there any difference? For example, cd ~; cd - cd ~; cd - and cd ~ && cd - seem to do the same. Which version is more portable, for example. will bash-subset be supported as an android shell or so?

+80
syntax bash shell multiplatform
May 27 '11 at 13:08
source share
7 answers

If the previous command failed with ; , the second will be launched.

But with && second will not work.

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

+116
May 27 '11 at 13:15
source share

I use && because a long time ago on the nearest computer:

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

but it didn’t help ...;)

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

+34
May 27 '11 at 18:33
source share

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

In cmd1 ; cmd2 cmd1 ; cmd2 , cmd2 is executed anyway.

Both designs are part of a POSIX compatible shell.

+15
May 27 '11 at 13:12
source share

Commands separated by a character ; are executed sequentially regardless of their completion status.

With && second command is only executed if the first is completed successfully (returns completion status 0).

This is described in man bash in the Lists section. I would expect that any Unix-like shell will support both of these operators, but I do not know specifically about the Android shell.

+5
May 27 '11 at 13:13
source share

&& means executing the next command if the previous one exited with status 0. Otherwise, use || to be executed if the previous command exits with a status not equal to 0 ; always executed.

It is very useful when you need to perform a certain action depending on whether the previous OK command has ended or not.

+4
May 27 '11 at 13:14
source share

&& allows conditional execution, whereas ; always executes the second command.

In particular. command1 && command2 , command2 will be executed only when command1 finished with exit 0 , the alarm went well, and in command1 ; command2 command1 ; command2 second command will always be executed regardless of the result of command1 .

+3
May 27 '11 at 13:15
source share

& & logically And in bash. Bash has a logic I. short circuit rating. This idiom is an easier way to express the following:

 cmd1;rc=$? if [ $rc -eq 0 ]; then cmd2 fi 

While; the version is simple:

 cmd1 cmd2 
+1
May 27 '11 at 15:48
source share



All Articles