Reputation: 1642
> [ 0 ]; echo $?
0
> [[ 0 ]]; echo $?
0
> (( 0 )); echo $?
1
> [ 1 ]; echo $?
0
> [[ 1 ]]; echo $?
0
> (( 1 )); echo $?
0
Is the behavior of (( 0 ))
just to match the typical numerical value of false in other languages? IE where true == 1
and false == 0
?
Upvotes: 2
Views: 269
Reputation: 30833
Barmar already gave the right reply for your main question.
A large part of your tests weren't about testing an arithmetic expressions value though but related to the test
command [
or the ksh
/bash
conditional compound command [[
.
In that case, if there is no operator, the test is string based, not arithmetic and the rule is very simple, everything not an empty string evaluates to true so only the empty string evaluates to false.
That's the reason all of your non arithmetic tests return a success status (0):
$ [ 0 ]; echo $?
0
$ [[ 0 ]]; echo $?
0
$ [ 1 ]; echo $?
0
$ [[ 1 ]]; echo $?
0
To get a failure status (1):
$ [ "" ]; echo $?
1
$ [[ "" ]]; echo $?
1
The test command accepts no string at all too:
$ [ ]; echo $?
1
but in that case the [[
command fails with both bash
and ksh
:
$ bash
$ [[ ]]; echo $?
bash: syntax error near ';'
$ ksh
$ [[ ]]; echo $?
ksh: syntax error: `;' unexpected
Upvotes: 2
Reputation: 781721
From the bash manual:
(( expression ))
The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the return status is0
; otherwise the return status is1
.
Your supposition is probably right, that it's to mimic the way many programming languages treat any non-zero value as truthy. You can then write:
if (( <expression> ))
then
...
fi
similar to how you would do it in C.
Upvotes: 7