FahmidasClassroom

Learn by easy steps

Bp3

Bash arithmetic operation

To perform arithmetic operations in Bash, the syntax is similar to other programming languages. Bash has the basic basic and advanced arithmetic operators which are described in this chapter. Many types of commands exist in bash to perform different types of arithmetic tasks. One of the major limitations of the bash script is that it can not calculate the fractional value of any arithmetic operation like other programming languages without using the `bc` command or `awk` command. The function of different arithmetic operators and the uses of different bash commands to do arithmetic operations have been discussed here.

Arithmetic operators

The uses of different arithmetic operators commonly used in bash have been mentioned below.

OperatorPurpose
+Add two numbers.
Subtract two numbers.
*Multiply two numbers.
/Divide two numbers.
%Find out the modulus of the division.
++Increment a number by 1
Decrement a number by 1
**Calculate the x to the power y of the number
<<Move the bit to the left for the particular positions.
>>Move the bit to the right for the particular positions.
~Calculate the bitwise NOT operation.
^Calculate the bitwise XOR operation.
&Calculate the bitwise AND operation.
|Calculate the bit-wise OR operation.

Different bash commands for arithmetic operations

Bash commands which are commonly used to perform mathematical operations in bash have been explained in this part.

`expr` command

The `expr` command in the Bash shell is a tool used for performing arithmetic and string operations in shell scripts. It is used to evaluate and print the value of an expression. The expression can be a combination of numbers, variables, and operators. The `expr` command can be used to perform basic arithmetic operations like addition, subtraction, multiplication, and division.

Create a bash file with the following script that shows the use of the `expr` command to do different types of arithmetic tasks.

#!/bin/bash 
#Add two numbers without a quotation 
echo -n "The output of 5+7 is " expr 5+7 
#Add two numbers with a quotation 
echo -n "The output of '5+7' is " 
expr '5+7' 
#Add two numbers with space 
echo -n "The output of 5 + 7 is " 
expr 5 + 7 
#Store the command output into a variable 
Var=`expr 5 - 2` 
echo "The output of the variable is $Var"

The output shows that the `expr` command can calculate the arithmetic expression when the numbers and the operators are used with the space.

c31

double bracket ‘(())’

The double bracket ‘(())’ is a notation used in the Bash programming language to perform arithmetic operations. This notation is also known as the arithmetic expansion or expression in Bash. It is used to evaluate mathematical expressions and return their results as an output. The double bracket notation is commonly used in Bash scripts to perform arithmetic operations like addition, subtraction, multiplication, and division. Additionally, it can also be used to compare numerical values, check for equality, and perform logical operations.

Create a bash file with the following script that shows the use of the ‘(())’ notation to do different types of arithmetic tasks.

#!/bin/bash

#Find out the result of the mathematical expression
#without the space
echo "The output of '8+3*6-2' is $((8+3*6-2))"

#Find out the result of the mathematical expression
#with the space
echo "The output of '8 / 4 + 5' is $(( 8 / 4 + 5 ))"

#Store the result in a variable
(( var = 33%5+7 ))
echo "The output of 33%5+7 is $var"

The output shows that the ‘(())’ notation can calculate the arithmetic expression whether the numbers and the operators are used with and without the space.

c32

`let` command

The `let` is another command of Bash to evaluate the arithmetic expressions. It is similar to the `expr` command, but it provides a more streamlined syntax for performing calculations. To use the `let` command, you simply need to preface your arithmetic expression with the keyword `let`. You can also perform more complex calculations using the `let` command, such as using parentheses to group operations or using comparison operators to evaluate conditions.

Create a bash file with the following script that shows the use of the ‘let’ command to do different types of arithmetic tasks.

#!/bin/bash

#Calculate the division
let "v1 = 15 / 5"
echo "The output of '15 / 5' is $v1"

#Calculate the remainder
let "v2=9%4"
echo "The output of '9%4' is $v2"

#Use of pre-increment operator
let ++v2
echo "The value of the variable after increment is $v2"

The output shows that the `let` command can calculate the arithmetic expression whether the numbers and the operators are used with and without the space.

c33

`bc` command

The `bc` command is a popular command-line calculator in Linux and Unix operating systems. It can be used to perform complex mathematical calculations and can also be used as a programming language. The full form of `bc` is “basic calculator”. The `bc` command can read input from standard input or a file and output the result of the calculations to the standard output. One of the key features of `bc` is its ability to handle floating-point calculations to a high degree of precision. This makes it a useful tool for scientific and engineering applications where precise calculations are necessary.

Create a bash file with the following script that shows the use of the ‘bc’ command to do different types of arithmetic tasks that will generate floating-point numbers.

#!/bin/bash

#Division with the bc command
echo -n "The division result of '10/7' with 'bc' is "
echo "10/7" | bc

#Division with the bc and -l option
echo -n "The division result of '10/7' with 'bc -l' is "
echo "10/7" | bc -l

#Division with the bc and scale value
echo -n "The division result of '10/7' with 'bc' and scale value is "
echo "scale=3; 10/7" | bc

The output shows that the `bc` command can calculate the arithmetic result with the fractional value and the fractional value with the specific number of digits after the decimal point.

c34

`awk` command

The `awk` command in Unix and Unix-like operating systems is a versatile tool for text processing and manipulation. One of the many functionalities of `awk` is its ability to perform arithmetic operations on numeric data.

Create a bash file with the following script that shows the use of the ‘awk’ command to calculate the arithmetic expression.

#!/bin/bash
#Define a mathematical expression
exp=124/5+10
#Print the output using the `awk` command
result=`awk "BEGIN {print $exp}"`
echo "The output of the '124/5+10' is $result"

The output shows that the `awk` command can calculate the arithmetic expression with the fractional value without using the `bc` command.

c35

Different advanced arithmetic operators

Some advanced-level operators to calculate the power and the bitwise operations have been shown in this part.

Use of the ‘**’ operator

The ‘**’ operator in bash, also known as the exponentiation operator, is particularly useful in bash scripts that require mathematical calculations. It is important to note that the ‘**’ operator has a higher precedence than other mathematical operators, such as multiplication or division

Create a bash file with the following script that shows the use of the ‘**’ operator to calculate the power of a number.

#Take the base value
read -p "Enter the base value: " x
#Take the power value
read -p "Enter the power value: " n
#Calculate the power value
result=$((x**n))
#Print the result
printf "%d to the power %d is %d\n" $x $n $result

The output shows that the power of 5 to the power of 3 is 125.

c36

Use of ‘<<‘ operator

The ‘<<‘ operator is used in bash as a left-shift operator for performing arithmetic operations. This operator shifts the bits of a number to the left by a specified number of positions. The number of positions to which the bits are shifted is determined by the second operand present after the ‘<<‘ operator. This operator has also other uses in bash.

Create a bash file with the following script that shows the use of the ‘<<’ operator to calculate the bitwise left shift operation.

#Take a number
read -p "Enter a number: " n1
#Take the total number of shift
read -p "Enter the number of shift: " n2
#Calculate the  number after the left shift
result=$((n1<<n2))
#Print the result
printf "The value after left shifting %d for %d times is %d\n" $n1 $n2 $result

The binary value of the 5 is 0101 and if this number is left shifted two times then the binary value is 10100 which is 20 in decimal.

c37

Use of ‘>>’ operator

The ‘>>’ operator in bash is used to shift the binary representation of a number to the right by a specified number of bits. This operator can be used for several different operations such as multiplication, division, and exponentiation.

Create a bash file with the following script that shows the use of the ‘>>’ operator to calculate the bitwise right shift operation.

#Assign a number
n1=7
#Assign another number for the right shift
n2=2
#Calculate the  number after the right shift
result=$((n1>>n2))
#Print the result
printf "The value after right shifting %d for %d times is %d\n" $n1 $n2 $result

The binary value of the 7 is 0111 and if this number is right-shifted two times then the binary value is 0001 which is 1 in decimal.

c38

Use of the ‘~’ operator

It is a unary operator which means that it operates on a single operand. Its function is to invert the bits of the operand. However, the ‘~’ operator has many other uses in bash.

Create a bash file with the following script that shows the use of the ‘~’ operator to calculate the complement value of a number.

#Take a number
read -p "Enter a number: " num
#Calculate the complement value
result=$(( ~num ))
#Print the result
printf "The complement value of %d is %d\n" $num $result

The binary value of the 5 is 0101 and the complement value of 0101 is -0110 which is -6.

c39

Use of the ‘^’ operator

The ‘^’ operator is used for arithmetic operations, specifically for exponentiation. This operator raises the first number to the power of the second number. But this operator can also be used for bitwise XOR operation which is shown here.

Create a bash file with the following script that shows the use of the ‘^’ operator to calculate the XOR value of the numbers.

#Take the first number
read -p "Enter a number: " n1
#Take the second number
read -p "Enter another number: " n2
#Calculate the XOR value
result=$(( n1^n2 ))
#Print the result
printf "The XOR value of %d and %d is %d\n" $n1 $n2 $result

The binary value of the 4 is 0100 and 3 is 0011. The XOR value of 0100 and 0011 is 0111 which is 7.

c40

Use of ‘&’ operator

This operator takes two binary numbers and performs a logical AND operation on each corresponding bit position in the numbers. The bitwise AND operation is often used in programming to manipulate binary data and perform logical operations on individual bits within a binary number.

Create a bash file with the following script that shows the use of the ‘&’ operator to calculate the AND value of the numbers.

#Take the first number
read -p "Enter a number: " n1
#Take the second number
read -p "Enter another number: " n2
#Calculate the AND value
result=$(( n1&n2 ))
#Print the result
printf "The AND value of %d and %d is %d\n" $n1 $n2 $result

The binary value of the 7 is 0111 and 3 is 0011. The AND value of 0111 and 0011 is 0011 which is 3.

c41

Use of the ‘|’ operator

It is called a pipe(|) symbol. It has many uses. One use of this operator is to compare the binary representation of two values and perform a logical OR operation on each corresponding bit position in the numbers.

Create a bash file with the following script that shows the use of the ‘|’ operator to calculate the OR value of the numbers.

#Take the first number
read -p "Enter a number: " n1
#Take the second number
read -p "Enter another number: " n2
#Calculate the OR value
result=$(( n1|n2 ))
#Print the result
printf "The OR value of %d and %d is %d\n" $n1 $n2 $result

The binary value of the 7 is 0111 and 3 is 0011. The OR value of 0111 and 0011 is 0111 which is 7.

c42

Exercise

  1. Write a bash script to calculate the average of three numbers with the 2 digits after the decimal point.
  2. Write a bash script to calculate the power of 95.
  3. Write a bash script to calculate the bitwise OR, AND, and XOR values of 12 and 14.

Summary

The uses of the most commonly used bash arithmetic operators and commands have been tried to be discussed in this tutorial to help new bash users.