Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program return codes and && bash symbol?

Tags:

c

bash

shell

unix

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

./foo && ./bar

Will first execute foo, and only if foo is "successful", it will then execute bar. However, this seems counter-intuitive when you consider that C programs, by convention, return 0 or exit(0) upon successful completion, which runs counter-intuitive to the behavior of the && operator. (Since in most languages, 0 is considered to be a 'falsey', and thus would stop the second statement from executing.) What am I missing?

like image 993
user1516425 Avatar asked Dec 08 '22 22:12

user1516425


2 Answers

The C language convention that 0 is false and anything else true, is just that, a convention. Bash (and unix shells in general), use the opposite convention: 0 is true, anything 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, the true command always exits with a status of 0, while false exits with a status of 1.

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

This can be rather disconcerting for someone who's used to the C convention, but it makes a lot more sense in shell terms that truth=success=zero exit status, while false=failure=nonxero exit status.

like image 197
Gordon Davisson Avatar answered Dec 23 '22 07:12

Gordon Davisson


You're not missing anything. You just have to keep in mind that true and false aren't fundamental concepts in the shell. success and failure are.

like image 25
Alan Curry Avatar answered Dec 23 '22 07:12

Alan Curry