When working with numbers in bash, when [[]] is preferred over (())

Just out of curiosity, there is always a reason to prefer something like:

while [[ $number -lt 10 ]] 

over

 while (( $number < 10 )) 

They seem to be doing the same thing. I'm wondering, maybe there is a performance advantage with one of them, or maybe portability problems with [[ ]] ?

+4
source share
3 answers

Also not standard, so portability is not a problem. If you are doing simple comparisons, the difference between them is small.

 if [[ $number -lt 10 ]] 

and

 if (( number < 10 )) 

in addition to the ability to drop $ from the second (since all lines are considered variable and dereferenced) and readability.

You may prefer [[...]] when your conditional code combines arithmetic and non-arithmetic tests:

 if [[ $number -lt 10 && $file = *.txt ]] 

vs

 if (( number < 10 )) && [[ $file = *.txt ]] 

You would probably prefer (( ... )) if your comparison included some calculations:

 if (( number*2 < 10-delta )) 

against unnecessarily complicated

 if [[ $(( number*2 )) -lt $(( 10-delta )) ]] 
+4
source

Some time ago, when you wanted to have any comparisons, you used the program "test", which was usually symbolic to mean "[".

So, you had expressions such as:

 if [ ..... ]; then 
Test

by default it is asciibetically compared, and if you need to do a numerical comparison, you need to use -lt / -gt and the like.

Then bash got its own internal test engine. To use it, you use [[.

So the same syntax you had before:

 if [ ... ]; then 

can be rewritten as:

 if [[ ... ]]; then 

and do the same, except that the comparison was done in bash itself and the fork / exec test program was not required.

Since now it does not call an external program, it is easier to add another method of comparison numerically. From here (()) appeared.

It has certain advantages, but it is usually overlooked that it imposes a numerical context.

This means you might have something like:

 i=1 (( i++ )) echo $i # will return 2 

In short, this is not a big deal for comparisons. but it pays to learn more about (()) and [[]] in man bash.

+3
source

(( and )) allow all complex arithmetic operators to be used, but [[ and ]] allow only the limited comparison defined in the man test

I prefer to use (( and )) since it also does not apply all interval limits. You can very well use:

 while ((number<10)) 

OR

 while ((number*2<10)) 

and etc.

0
source

Source: https://habr.com/ru/post/1487489/


All Articles