Bash Arithmetic
Simple arithmetic with (( ))
Section titled “Simple arithmetic with (( ))”#!/bin/bashecho $(( 1 + 2 ))Output: 3
# Using variables#!/bin/bashvar1=4var2=5((output=$var1 * $var2))printf "%d\n" "$output"Output: 20
Arithmetic command
Section titled “Arithmetic command”let
let num=1+2 let num="1+2" let 'num= 1 + 2' let num=1 num+=2You need quotes if there are spaces or globbing characters. So those will get error:
let num = 1 + 2 #wrong let 'num = 1 + 2' #right let a[1] = 1 + 1 #wrong let 'a[1] = 1 + 1' #right(( ))
((a=$a+1)) #add 1 to a ((a = a + 1)) #like above ((a += 1)) #like aboveWe can use (()) in if. Some Example:
if (( a > 1 )); then echo "a is greater than 1"; fiThe output of (()) can be assigned to a variable:
result=$((a + 1))Or used directly in output:
echo "The result of a + 1 is $((a + 1))"Simple arithmetic with expr
Section titled “Simple arithmetic with expr”#!/bin/bashexpr 1 + 2Output: 3
Syntax
Section titled “Syntax”Parameters
Section titled “Parameters”| Parameter | Details |
|---|---|
| EXPRESSION | Expression to evaluate |
Remarks
Section titled “Remarks”A space (” ”) is required between each term (or sign) of the expression. “1+2” won’t work, but “1 + 2” will work.