Basically "&&" and "||" are logical operators, meaning "AND" and "OR".
Every command has a return value (=error level, $?) and the Unix convention is that a return value of "0" (=TRUE) means successful completion, everything else means failing for different reasons. A program might return the following values, for instance:
0 success
1 file(s) not found
127 parameter error - user gave a command line which doesn't make sense
"AND" only is true when both parts are true. "A AND B" only evaluates to true if A is TRUE AND B is TRUE, otherwise it is false. Because the programmers of these operators know this too they implemented "&&" to work this way: first run A, and if this returns FALSE there is no sense in attempting B, because the complete expression can never be TRUE, regardless of what B returns. This means in turn, that B is only attempted if A returns true.
Therefore the following two constructs are identical:
command1 && command2
if command1 ; then
command2
fi
The same goes for "||", which is a logical OR. As it is an EXCLUSIVE OR, it is only true if exactly one of its operands are true. It is false if both are false and it is false if both are true. Therefore the system again runs the first operand and if this returns TRUE, it will not even attempt B, because the whole cannot result in TRUE any more. Only if A returns FALSE it will attempt B. In other words: the following two are equivalent:
command1 || command2
if ! command1 ; then
command2
fi
Here is an example: we will use "cat", which returns an error level of "0" if it can display a file, but returns non-0 if the file name specified doesn't exist (or is not readable, ...).
cat /etc/passwd >/dev/null
This will display the contents of /etc/passwd
to <stdout>, which is redirected to /dev/null. Basically this command will show nothing on the screen, but it will still produce a return level.
cat /etc/passwd >/dev/null; echo error level is $?
cat /some/path/blabla >/dev/null; echo error level is $?
The second file mentioned is supposed to not exist (should you happen to actually have the file "/some/path/blabla", replace it with another filename). Both commands will produce no output, but both will have different error levels.
Now we use this device with our logical operators:
cat /etc/passwd >/dev/null && echo "file /etc/passwd does exist"
cat /etc/passwd >/dev/null || echo "file /etc/passwd does not exist"
cat /some/path/blabla >/dev/null && echo "file /some/path/blabla does exist"
cat /some/path/blabla >/dev/null || echo "file /some/path/blabla does not exist"
All the first commands in each line are executed, but notice, that only the first and the fourth of the second commands are executed, depending on the existence of the mentioned files. Basically these lines are tests for the existence of the respective files, so it would have been easier to do than this. It should explain how the operators work, though.
I hope this helps.
bakunin