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 ?
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 ?
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
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)
(())
, booleans are C-style (0 is falsey)
– D. Ben Knoble
Jun 17 '19 at 01:05
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.