You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Joachim Ansorg edited this page Nov 12, 2021
·
6 revisions
$/${} is unnecessary on arithmetic variables.
Problematic code:
echo$(($n+${arr[i]}))
Correct code:
echo$((n + arr[i]))
Rationale:
The $ or ${..} on regular variables in arithmetic contexts is unnecessary, and can even lead to subtle bugs. This is because the contents of $((..)) is first expanded into a string, and then evaluated as an expression:
The $ is unavoidable for special variables like $1 vs 1, $# vs #. It's also required when adding modifiers to parameters expansions, like ${#var} or ${var%-}. ShellCheck does not warn about these cases.
The $ is also required (and not warned about) when you need to specify the base for a variable value:
$ a=09
$ echo$((a +1))# leading zero forces octal interpretation
bash: 09: value too great for base (error token is "09")
$ echo$((10#a+1))
bash: 10#a: value too great for base (error token is "10#a")
$ echo$((10#$a+1))
10