bash math operation code example

Example 1: how to do math in bash

# Basic syntax:
# Subtraction
expr 1 - 1
0
# Addition
expr 1 + 1
2
# Assign result to a variable
myvar=$(expr 1 + 1)
echo $myvar
2
# Addition with a variable
expr $myvar + 1
3
# Division
expr $myvar / 3
0
# Multiplication
expr $myvar \* 3
6

Example 2: arithmetic operation in bash

#!/bin/bash
x=5
y=10
ans=$(( x + y ))
echo "$x + $y = $ans"

Example 3: how to perform mathematical operations in shell script

#!/bin/sh

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a is equal to b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi