Bash: let statement vs assignment

LinuxBashUnix

Linux 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIDDQDView Question on Stackoverflow
Solution 1 - LinuxAleks-Daniel Jakimenko-A.View Answer on Stackoverflow