C, but the symbol && bash?

In bash, we can use the && operator to execute two commands. For instance:

./foo && ./bar 

First, foo will execute, and only if foo is "successful" will it execute bar . However, this seems contradictory if you think that C programs by convention return 0 or exit(0) after successful completion, which contradicts the intuition of the behavior of the && operator. (Since in most languages, 0 is considered β€œfalse” and thus stops the execution of the second statement.) What am I missing?

+4
source share
3 answers

You have not missed anything. You just need to keep in mind that true and false are not fundamental concepts in the shell. success and failure .

+5
source

A C convention in which 0 is false and something else is true is just a convention. Bash (and unix shells in general), use the opposite convention: 0 is true, something else is false.

 $ if ( exit 0 ); then echo true; else echo false; fi true $ if ( exit 1 ); then echo true; else echo false; fi false $ if ( exit 2 ); then echo true; else echo false; fi false 

Because of this, true always exits with status 0, and false exits with status 1.

 $ true; echo $? 0 $ false; echo $? 1 

This can be quite embarrassing for those who are used to the C convention, but in terms of the shell there is a lot more sense: true = success = zero exit status, and false = fail = noxero exit status.

+7
source

The Bash && operator is missing:

command1 && command2
command2 is executed if and only if command1 returns exit status 0.

+2
source

All Articles