This tutorial explains about arthematic expersssions and expansion.

Bash Athematic expressions

Arthematic expressions are used to perform mathematical operations

expressions is a term used in math to denote an operation. It contains operands and operatorto perform mathematical operatoions. a<b is an expression. It may contains binary or unary operators

In bash, Experssions are created using (()) brackets with the operands and operators as arguments. ((a)) is an bash expression.

Syntax is

((expression))

expression are mathematical operations, It can contains sub expressions separated by comma.

result=$((12 + 11))
echo "$result"

Arthematic expressions are constructed using below operators

  • Arthmatic Operators
  • Comparision Operator

Comparision operators used to check one with another by comparing values The operators (<, <=, >, >=, ==, !=)

a=10
b=2
if ((a > b)); then
    echo "a is greater than b"
fi
  • Logical Operators
  • Conditional Statements

Bash Athematic Expansion

Expansion are same as expressions, It calculates the value of an expression and result is replaced with an value. It always prefixed by dollar sign.

$((expression))

For example, calculate the average of two numbers, print the result. Here used expansion syntax, It evaluates expression and result is replaced with an output of expression.


first=12
second=2
echo "The average is $(((first+second)/2))".

When to Use arthematic expressions and expansions

[[]] is used to test an expression, returns boolean value(1 or 0). This will be used in the following cases

  • Use artheatic expression

    • To perform mathematicl operations and comparision
  • Use artheatic expression [[]

    • Comparision of strings and numbers
    • Check file or directory exists