Bash Arithmetic
Bash provides excellent support for basic arithmetic operations.
From the source: GNU bash manual: Shell Arithmetic.
Basic Arithmetic Operations
Basic arithmetic is performed as follows:
echo "Addition: $((2 + 2))" echo "Subtraction: $((4 - 2))" echo "Multiplication: $((2 * 3))" echo "Division: $((6 / 2))"
The spaces are for readability only, they could be left out.
Integer variables
A variable can be declared as containing an integer:
declare -i index index=2+3 index*=2
Subsequent assignments to index will be interpreted as arithmetic expressions, so at the end of the script, index holds the value 10. See also Shell Parameters.
In many cases, storing numbers in variables which are not explicitly declared as integer will work just fine. However:
- Declaring a variable as integer will prevent it from holding non-integer values, which helps detect bugs.
- The next person who has to understand the code will appreciate the hint.
- The bash interpreter has more information about what you are doing, which is a good thing.
Arithmetic expressions with variables
Arithmetic looks as follows in bash:
declare -i index=2 index=$((index + 1)) echo "$((index * $index))" # outputs 9
Note that variables can be referenced without $ inside arithmetic expressions.
Conditionals
The test (builtin) command tips describes how to compare numbers in conditionals.