lanza
lanza

Reputation: 1642

Why does `(( 0 ))` have a return value of 1 in .sh script?

> [ 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

Answers (2)

jlliagre
jlliagre

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

Barmar
Barmar

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 is 0; otherwise the return status is 1.

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

Related Questions