Linux Command Reference ยท Shell Builtins
Bash let command
Reference for the Bash let builtin: evaluate integer expressions, assign with +=, ++ and ternaries, use bases, and understand its exit status versus (( )).
let evaluates one or more arithmetic expressions with Bash's integer arithmetic. It handles assignments, increments, comparisons, bit operations and the ternary operator, and it creates variables as a side effect. It prints nothing; the interesting parts are the variables it changes and its exit status.
let is a Bash builtin (also in ksh and zsh), not POSIX. Today most people write (( expr )) instead, which is the same evaluator with nicer syntax: no need to quote spaces and no let word. Reading old scripts still requires knowing let.
let "x = 5 * 3" let x++ y+=2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
let ARG [ARG ...]
| Name | Description |
|---|---|
ARG |
An arithmetic expression. Each argument is evaluated separately, so quote any that contain spaces or *, <, >, ` |
Operators follow C: + - * / %, ** (power), ++ --, = += -= *= /= %= <<= >>= &= ^= |=, comparisons, && || !, bit operators & | ^ ~ << >>, the ternary ?:, and the comma. Numbers can be 0x hex, 0 octal or base#number (2 to 64).
Returns: 1 (false) if the last expression evaluates to 0, otherwise 0 (true). An invalid expression gives status 1 and an error message.
Edge cases: division by zero is an error; 09 is an error because a leading zero means octal; arithmetic is 64-bit signed and wraps silently.
Usage notes
- Exit status is inverted.
let "x = 0"returns1. That trips scripts running underset -e; add|| true, or usex=$(( ... )), which is always a successful assignment. - Prefer
(( ))in new code.(( x = a + b ))needs no quotes and reads better.letis the same engine in command form. - No dollar signs needed, but they work:
let "y = $x + 1"expands first, which risks word splitting. Use plain names. - Integers only. There is no floating point;
let "x = 7 / 2"gives3. Usebcorawkfor decimals. - Unset or non-numeric variables count as 0 in expressions; a string that looks like a name is looked up recursively, which can give odd results.
- Quoting is not optional with spaces.
let x = 5means three arguments,x,=and5, and fails. - Several expressions at once:
let a=1 b=2 c=3is fine because there are no spaces inside each. - Not portable.
sh(dash) has nolet; use$(( ))there.
Related
expr,bc,test,declare(-i), Arithmetic expansion- Lessons: Arithmetic, Variables, Loops