Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should variable references be $-prefixed in arithmetic for loops (arithmetic contexts)?

All of these options below work for setting i to count.

count=5

for (( i=count; i>=0; i-- )); do 
    echo "$i"
done

for (( i=$count; i>=0; i-- )); do 
    echo "$i"
done

for (( i=$((count)); i>=0; i-- )); do 
    echo "$i"
done

for (( i=${count}; i>=0; i-- )); do 
    echo "$i"
done

Which is correct or preferred?


1 Answers

Generally, in arithmetic contexts such as ((...)) and $((...)), reference variables by name only, without the $ prefix (as your commands are already doing with respect to variable $i):

for (( i=count; i>=0; i-- )); do 
    echo "$i"
done
  • Since ((...)) is an arithmetic context itself, there is no good reason to use a separate, expanding arithmetic context - $((count)) - inside of it.

  • Note that $count and ${count} are equivalent, and enclosing the variable name - count - in { and } after $ is only necessary to disambiguate the variable name from subsequent characters that can also legally be part of a variable name (which doesn't apply to your commands).
    As Gordon Davisson points out, some people choose to always use the ${var} form for visual clarity.

While $-prefixed variable references in arithmetic contexts do work, there is rarely a good reason to use them: the use of $ introduces an extra expansion step before the arithmetic evaluation, which is not only unnecessary, but can result in different behavior, as explained in rici's helpful answer.

The only cases where you need the $ prefix:

  • To reference positional and special parameters (variables) that can only ever be referenced with $: Thanks, rici.

    • Positional parameters: $1, $2, ...
    • The count of positional parameters: $#
    • Special parameters: $?, $$, $! (there are others, but they are not generally numeric - see chapter Special Parameters in man bash).
  • If you need a nonzero default value that you provide via a parameter expansion; e.g., ${count:-2} defaults to 2 if $count is unset or empty.

  • If you want to use a variable value as an operator rather than operand; e.g.:
    op='*'; echo $(( 2 $op 2 )) - this wouldn't work with just op.

like image 63
mklement0 Avatar answered Sep 06 '26 12:09

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!