Reputation: 1963
When running this line of bash
ls file.txt && echo "Exists" || echo "Not exists"
Bash echos "Exists" if the file exists, and "Not exists" if it doesn't. So the logic is
true && echo "Exists" || echo "Not exists"
The question is: how does bash decide if a command is successful? The ls command has 0 as successful exit code, how can bash interpret that 0 means true, in this case?
Upvotes: 2
Views: 477
Reputation: 8589
It is just a convention for exit codes that works for basically all modern Operating Systems for EXIT_SUCCESS
If we want to make a parallel example in Web, a 404 return code means Page not found.
Also in this case the choice of 404 is simply a convention.
In BASH, basically, any exit code that is not 0 is some sort of error.
Here's the complete list of BASH reserved exit codes:
http://tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
"Why specifically 0?", you might ask.
In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application.
On most operating systems returning 0 is a success status, a very succinct way of reporting that "The program worked fine".
In C++ it is optional to type "return 0;" at the end of the main function because the compiler includes it automatically.
The specific logic implemented in the program itself will declare if program execution was fine or not.
For example I can implement a program that takes care of deleting files and, in case I get an error during file removal I will return -1, otherwise at the end of the removal process, in case of no errors / exceptions, I will return 0.
You can have some fun and go checking the source code of Linux commands to learn more.
Here's ls, for example.
Edit after the comment
The right side of && will only be evaluated if the exit status of the left side is zero (i.e. true).
On the other hand || is the opposite, it will evaluate the right side only if the left side exit status is non-zero (i.e. false).
BASH's behaviour with 0 is only related to this kind of operators.
In other words:
$ false && echo working
$ true && echo working
working
$ true || echo working
$ false || echo working
working
Upvotes: 4