Bash: let statement vs assignment
LinuxBashUnixLinux Problem Overview
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?
Linux Solutions
Solution 1 - Linux
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