0

I am running this on Linux:

$ number=4 $ test $number -eq 4 $ echo $? 0 $ test $number -lt 2 $ echo $? 1 

Are the results (0 and 1) true ?

6

3 Answers 3

4

On Unix systems, utilities return a zero exit-status if what they did went well, if it succeeded without errors etc. If a utility fails, it returns a non-zero exit status.

This way, it's possible to tell a user with the exit-status what when wrong (see e.g. the "EXIT VALUES" or similar section of some manuals, for example the manual of rsync). In short, if the operation succeeded, the exit-status is zero and if it's not zero, it failed and the exit-status may say why it failed.

The test utility, which you use, follow this pattern in that if a comparison succeeded (it's "true"), it returns zero. If the comparison (or whatever operation it carries out) fails (it's "false"), it returns a non-zero exit-status.

The if keyword takes a utility and acts on its exit-status. If the utility returns a zero exit-status, it takes the default branch, otherwise it takes the else branch:

if test 4 -eq 3; then echo 4 is 3 else echo 4 is not 3 fi 

if can take any utility:

if grep -q 'secret' file.txt; then echo file.txt contains secret else echo file.txt does not contain secret fi 
if mkdir mydir; then echo created directory mydir else echo failed to create directory mydir fi 
1
  • Thank you for your interest. Commented Jun 16, 2019 at 21:48
3

By convention, 0 means the operation was a success and anything other than 0 is an error. So, if $? is 0, then the test was successful and if it is not 0, for example if it is 1, the test failed.

You can see this a bit more clearly perhaps if you run this:

$ number=4 $ if test $number -eq 4; then echo "YES ($?)"; else echo "NO ($?)"; fi YES (0) $ if test $number -lt 2; then echo "YES ($?)"; else echo "NO ($?)"; fi NO (1) 
2
  • Thank you @terdon you explained clearly. Commented Jun 16, 2019 at 21:48
  • With the caveat, of course, that in (()), booleans are C-style (0 is falsey) Commented Jun 17, 2019 at 1:05
0

The shell is not C. In C 0 is false, everything else is true. In the shell 0 is true/success, everything else is false. This is because there are many ways to fail, but one way to succeed.

Specifically from the info page, of test.

Exit status: 0 if the expression is true, 1 if the expression is false, 2 if an error occurred. 
1
  • Thank you so much you explained well. Commented Jun 16, 2019 at 21:47

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.