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?
Bash let is a built-in command in Linux systems used for evaluating arithmetic expressions. Unlike other arithmetic evaluation and expansion commands, let is a simple command with its own environment. The let command also allows for arithmetic expansion.
The let command is used to evaluate arithmetic expressions on shell variables. Syntax: let [expression] Options: Basic arithmetic operators : The addition(+), subtraction(-), multiplication(*), division(/) and modulus(%) operators can be used in the expression with the let command.
Description. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.
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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With