0
0
Bash-scriptingHow-ToBeginner · 3 min read

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 arithmetic
  • expression: 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

UsageDescription
let var=expressionEvaluate arithmetic expression and assign to var
let var+=valueAdd value to var
let var-=valueSubtract value from var
let var*=valueMultiply var by value
let var/=valueDivide 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.