71

What is the difference between assigning to a variable like var=foo and using let like let var=foo? Or cases like var=${var}bar and let var+=bar? What are the advantages and disadvantages of each approach?

IDDQD
  • 3,543
  • 8
  • 29
  • 40

1 Answers1

81

let does exactly what (( )) do, it is for arithmetic expressions. There is almost no difference between let and (( )).

Your examples are invalid. var=${var}bar is going to add word bar to the var variable (which is a string operation), let var+=bar is not going to work, because it is not an arithmetic expression:

$ var='5'; let var+=bar; echo "$var"
5

Actually, it IS an arithmetic expression, if only variable bar was set, otherwise bar is treated as zero.

$ var='5'; bar=2; let var+=bar; echo "$var"
7
Aleks-Daniel Jakimenko-A.
  • 10,335
  • 3
  • 41
  • 39
  • 1
    One difference is that `let` allows some degree of indirection: `a=b; b=3; let $a+=1; echo $b;`. The argument to `let` undergoes parameter expansion before being evaluated (which I don't think I saw mentioned in the link you posted). – chepner Sep 09 '13 at 23:47
  • 7
    Actually, scratch that. I thought that after `a=b; b=3`, the two commands `(( a+=1 ))` and `(( $a+=1 ))` would be equivalent, but they aren't. The first seems to replace `a` with the value of `b`, then increments, leaving the value of `b` untouched. The second increments `b` while leaving `a` set to the string `b`. – chepner Sep 09 '13 at 23:52
  • [this](https://github.com/koalaman/shellcheck/wiki/SC2219) explains why `((...))` should be used in favor of `let` – Udo Jun 01 '23 at 13:37