Why 0 is true but false is 1 in the shell?

httpinterpret picture httpinterpret · May 29, 2010 · Viewed 71.3k times · Source
false; echo $?

The above will output 1, which is contradictory with all other programming languages I know.

Any reason in this?

Answer

Carl Norum picture Carl Norum · May 29, 2010

It's a convention, but a particularly useful one when you think about it. In general, if a program succeeds that's all you need to know. If it fails, however, you might need to know all kinds of information about the failure - why it happened, how to fix it, etc. Having zero mean 'success' and non-zero mean failure lets you can check pretty easily for success, and investigate the particular error for more details if you want to. A lot of APIs and frameworks have a similar convention - functions that succeed return 0 and and those that fail give back an error code describing the particular failure case.