Why can I refer to a variable inside (( )) without the $ symbol?

In ABS guide, I could see below snippet

var1=5
var2=4

if (( var1  > var2 ))
then
echo "$var1 is greater than $var2"
fi

I am not able to understand, why we don’t need $ symbol. I added $ symbol, shellcheck shows "$ symbol is not necessary on arithmetic variables".

I am still not able to understand how that dereferencing of var1 and var2 works…

>Solution :

Expressions inside ((...)) are evaluated in arithmetic context. Strings which can be variable names are considered as variables whose values are integers, since evaluating these strings as literal strings makes no sense in arithmetic context. These considerations are also valid for C style for loops: in for ((i = 0; i < 10; ++i)), preceding i with $ is not necessary (but it may be necessary, depending on the context, within the body of the loop).

Leave a Reply