If an operator with arithmetic comparison behavior in bash

I am learning bash, and I noticed something strange that I cannot (yet) explain. At school, I found out that the if statement evaluates 0 as true and 1 as false, so it can be used with a status code from another command. Now my question is: why is this happening:

echo $((5>2)) #prints 1 echo $((5<2)) #prints 0 if ((5>2)) ; then echo "yes" ; else echo "no" ; fi #prints yes if ((5<2)) ; then echo "yes" ; else echo "no" ; fi #prints no 

This does not seem logical. How does bash know that I'm using an arithmetic expression and not another command?

+5
source share
3 answers

$((...)) is an arithmetic expression; it expands to the value of the expression inside the parentheses. Since this is not a command, it does not have an exit status or return value. A Boolean expression evaluates to 1 if it is true, 0 if it is false.

((...)) , on the other hand, is an arithmetic statement. This is a team in itself that works by evaluating its body as an arithmetic expression, and then looking at the resulting value. If the value is true, the command completes successfully and has an exit status of 0. If the value is false, the command completes with an error and has an exit status of 1.

A good idea when learning bash stop thinking about conditions in if , while loops, etc. as true or false, but rather if the teams succeed or fail. After all, shell languages ​​are not designed to process data; they are the glue language for launching other programs.

+2
source

You are misleading the output of command substitution and the return value of an arithmetic context.

The result of substituting command 1 for true and 0 for false.

The return value (( )) is 0 (success) if the result is true (i.e., nonzero) and 1 if it is incorrect.

if looks at the return value, not at the output of the command.

+7
source

In the bash manual:

((expression))

The expression is evaluated in accordance with the rules described below in the section ARIMETIC EVALUATION. If the value of the expression is nonzero, the return status is 0; otherwise, the return status is 1 . (My emphasis.)

So essentially in the boolean context, ((expression)) gives the opposite of what $((expression)) will give.

+2
source

All Articles