tags:

views:

305

answers:

5
false; echo $?

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

Any reason in this?

+7  A: 

It's just a convention that a 0 exit code means success. EXIT_SUCCESS will be 0 on almost every modern system.

EDIT:

"why both test 0 and test 1 returns 0(success) ?"

That's a completely different question. The answer is that passing a single argument to test always results in success unless that argument is the null string (""). See the Open Group documentation.

Matthew Flaschen
Then why both `test 0` and `test 1` returns 0(success) ?
httpinterpret
@httpinterpret, `test` doesn't test numerical values. It tests for whether or not that string is the null string. `man test` for more information.
Carl Norum
+1  A: 

Typically programs return zero for success, non-zero for failure; false returns 1 because it's a convenient non-zero value, but generally any non-zero value means failure of some sort, and many programs will return different non-zero values to indicate different failure modes

Michael Mrozek
Downvote? For what?
Michael Mrozek
+7  A: 

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.

Carl Norum
+4  A: 

Bash is a programming (scripting) language, but it's also a shell and a user-interface. If '0' was error, then the program could only present one kind of error.

However in Bash, any 'non-zero' value is an error, and we may use any number from 1-255 to represent an error. This means we can have many different kinds of errors. '1' is a general error, '126' means that a file cannot executed, '127' means 'command not found', etc. Here's a list of Bash Reserved Exit Codes showing some of the most common exit codes.

There are also many kinds of success (exit status is '0'). However, a 'success' will allow you to proceed to the next step-- you can like print results to a screen, or execute a command, etc.

Stefan Lasiewski
A: 

AFAIK this come from the C convention that you should return 0 if succeded. See:

man close

Most of the C (POSIX) api is build like this. http://en.wikipedia.org/wiki/C_POSIX_library

mathk