Search code examples
shelllogicreturn-valueradix

shell's logic AND, cmd1 && cmd2, it's reversed, right?


We know && means logical AND, so:

true && true  => true
false && true => false

When we work in Shell (Bash here), successful command call returns 0. Does the shell change 0 to non-zero before AND operation? Or Shell just reverse the normal logics?

As an example:

cat file1 && cat file2

file2 will be cat-ed only if file1 can be cat-ed.


Solution

  • In Bash, logical true is represented as 0 while logical false is represented as a non-zero value. This allows the exit value of a command to be used in a logical operation.

    You can find out more by browsing the documentation on bash operators.

    One common idiom is to chain commands using && so that if any command in the chain fails, the following commands are not executed:

    cmd1 && cmd2 && cmd3