Table of Contents

About

arithmetic in bash

part of compound expression .

Example

  • Counter
counter=0
(( counter + 1))
counter=$((counter+1))
  • Simple addition
echo One plus One is $((1+1))
echo One plus One is 2

Syntax

(( arithmetic expression ))
# or to capture the output
$((arithmetic_expression))
# or
let arithmetic_expression [arithmetic_expression, ...]

where let is the let command

If the value of the expression is:

  • non-zero, the return status is 0;
  • otherwise the return status is 1.

Management

Variable

If the variable has its integer attribute set (see Bash - Declare (Variable declaration and attribute)), then value is evaluated as an arithmetic expression even if the $((...)) expansion is not used.

Operator

In the context where an assignment statement is assigning a value to a shell variable, the += operator can be used to append to or add to the variable’s previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable’s current value, which is also evaluated.

Comparison

  • As number
if (( a > b )); then
    ...
fi
if [ "$a" -gt "$b" ]; then
    ...
fi