Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: let statement vs assignment

Tags:

linux

bash

unix

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?

like image 894
IDDQD Avatar asked Sep 09 '13 18:09

IDDQD


People also ask

What does let do in bash?

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.

What is let in shell script?

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.

What is the use of 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.

What does $() mean in bash?

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.


1 Answers

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 
like image 181
Aleks-Daniel Jakimenko-A. Avatar answered Sep 26 '22 05:09

Aleks-Daniel Jakimenko-A.