Session and utilities
The let command
Evaluates integer arithmetic expressions and stores the results in variables.
Copy-ready examples
$ let x=2+3 && echo $xcalculates and shows the result.Example output
5
$ let "n = 2 * 3" && echo $nthe quotes allow spaces inside the expression.Example output
6
$ let "a=5" "b=a*2" && echo $beach argument is an expression. Inside let, the names do not take a $.Example output
10
$ x=10; let x-=3 && echo $xuses compound operators such as -=.Example output
7
$ let x=7/2; echo $xworks with integers only: division is truncated.Example output
3
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| bash: let: x=08: value too great for base (error token is "08") | A number with a leading zero is read as octal, and 8 is not a valid octal digit. | Remove the zero: let x=8. |
| bash: let: =: syntax error: operand expected (error token is "=") | You wrote spaces without quotes: the shell passes each word as a separate argument. | Quote the expression, for example let "x = 2 + 3", or remove the spaces. |
| bash: let: 1/0: division by 0 (error token is "0") | The divisor in the expression is 0, and division by zero is not defined. | Check the divisor before the calculation with an if. |
Typical mistakes
- let returns 1 when the last result is 0: with && or with set -e, that can stop your script even when the calculation is correct.
- Without quotes, spaces, *, parentheses or < are split or expanded by the shell before let sees them.
- A number with a leading zero is read as octal: let x=08 gives an error.
Differences from similar commands
FAQ
How does it differ from $(( ))?
let stores the result in variables without printing it; $(( )) returns the value to use inside a command, such as echo $((2+3)).
Why does let return code 1 when the calculation is correct?
Because its code reflects the result of the last expression: 1 if it is 0. That is why let x=0 && echo hi prints nothing.
Can I calculate with decimals?
No: bash arithmetic is integer only and division truncates. For decimals use bc.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course