Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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

while [[ $number -lt 10 ]]

over

while (( $number < 10 )) 

They seem to do the same thing. I'm wondering if maybe there is a performance benefit with one of them or maybe some portability concerns with [[ ]]?

like image 655
rage Avatar asked Mar 23 '23 11:03

rage


1 Answers

Neither is standard, so portability is not an issue. If you are only performing simple comparisons, there is little difference betwee

if [[ $number -lt 10 ]]

and

if (( number < 10 ))

aside from the ability to drop the $ from the second (since all strings are assumed to be variables and dereferenced) and readability.

You might prefer [[...]] when your conditional 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 involved some computations:

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

vs the needlessly complex

if [[ $(( number*2 )) -lt $(( 10-delta )) ]]
like image 150
chepner Avatar answered Apr 06 '23 11:04

chepner