let
Perform arithmetic calculations within shell scripts
TLDR
Evaluate a simple arithmetic expression
Use post-increment and assignment in an expression
Use conditional operator in an expression
Display help
SYNOPSIS
let expression [expression ...]
PARAMETERS
expression
An arithmetic expression to be evaluated. Multiple expressions can be provided, separated by spaces.
DESCRIPTION
The let
command in Linux is a built-in shell command that evaluates arithmetic expressions. It's primarily used within shell scripts to perform calculations and assign the results to variables. let
is a legacy command and is generally superseded by more modern and flexible arithmetic evaluation constructs within the shell (such as $((...))
). It simplifies basic arithmetic operations, variable assignments and some bitwise operations directly within the shell environment without needing external tools like bc
or expr
.
The let
command treats each argument as an arithmetic expression to be evaluated. Multiple expressions can be provided as separate arguments or joined with spaces. The command performs integer arithmetic and supports common operators like addition, subtraction, multiplication, division, and modulo. The result of the last evaluated expression is set as the exit status; a non-zero result corresponds to a zero exit status, and a zero result corresponds to a non-zero exit status. Variable names can be used directly in expressions, and their values are automatically substituted. Variables do not need to be prefixed with $
.
CAVEATS
let
only supports integer arithmetic. It does not handle floating-point numbers. The exit status can be confusing. It is based on the arithmetic result not success or failure.
ALTERNATIVES
The preferred alternative to let
is using the $((...))
arithmetic expansion. This provides greater flexibility and is generally easier to read. Example: result=$(( a + b * 2 ))
.
EXIT STATUS
The exit status of let
is 0 if the last expression evaluates to a non-zero value, and 1 if the last expression evaluates to zero. This is the opposite of most other commands which return zero for success.
EXAMPLES
let "x = 5 + 3": Assigns the value 8 to the variable x.
let "count++": Increments the value of the variable count by 1.
let "result = a * b": Multiplies the values of variables a and b and assigns the result to the variable result.
HISTORY
let
is a relatively old command, dating back to early versions of the Bourne shell and subsequently adopted by other shells like bash. It provided a convenient way to perform arithmetic operations within shell scripts before more modern constructs like $((...))
became widely used. While still functional, it's considered less preferred than the more flexible and readable alternatives.