How to Use let in Bash: Syntax and Examples
In bash,
let is used to perform arithmetic operations on variables. You write expressions inside let without spaces around operators, and it updates the variable values directly.Syntax
The basic syntax of let is: let expression. The expression can include variables and arithmetic operators like +, -, *, /, and %. No spaces should be around the operators inside the expression.
Example parts:
let: the command to evaluate arithmeticexpression: the math operation, e.g.,count=5+3
bash
let count=5+3
Example
This example shows how to use let to add, subtract, multiply, and divide variables in bash.
bash
count=10 let count=count+5 let count=count-3 let count=count*2 let count=count/4 echo $count
Output
6
Common Pitfalls
Common mistakes include putting spaces around operators, which causes errors, or forgetting to use variables properly.
Wrong: let count = count + 1 (spaces cause error)
Right: let count=count+1
bash
count=1 # Wrong usage (will cause error) # let count = count + 1 # Correct usage let count=count+1 echo $count
Output
2
Quick Reference
| Usage | Description |
|---|---|
| let var=expression | Evaluate arithmetic expression and assign to var |
| let var+=value | Add value to var |
| let var-=value | Subtract value from var |
| let var*=value | Multiply var by value |
| let var/=value | Divide var by value |
Key Takeaways
Use
let to perform arithmetic operations on bash variables without spaces around operators.Always write expressions like
let count=count+1, not with spaces.let updates variables directly and returns success or failure based on the result.You can use
let for addition, subtraction, multiplication, division, and modulo operations.Remember to echo variables after
let to see the updated values.