How to use Bash Operators

Let’s look at Bash Operators and see how you can use them in your Bash scripts. This post will focus on arithmetic operators to help you do mathematical operations in Bash. We will also look into relational operators allowing us to compare values.

Arithmetic Bash Operators:

We use these operators to perform mathematical operations like addition, subtraction, and others. They work in the same both in the terminal as well as in scripts. You can do these mathematical operations using the expr (evaluate expressions) command or via double braces. Let us see some examples for each of these below.

Addition ( + ) – Adds numbers
u[email protected]:~$ echo $(( 3 + 8 ))
11

[email protected]:~$ expr 3 + 8
11
Multiplication ( * ) – Multiplies numbers

Note that you need to use \ before * when using the expr command; otherwise, you will get an error.

[email protected]:~$ echo $(( 3 * 8 ))
24

[email protected]:~$ echo $(( 3 \* 8 ))
24

[email protected]:~$ echo $(( 3 * 8 ))
expr: syntax error
Subtraction (  ) – Subtracts numbers
[email protected]:~$ echo $(( 8 - 3 ))
5

[email protected]:~$ expr 8 - 3 
5
Division ( / ) – Divides numbers
[email protected]:~$ echo $(( 8 / 4 ))
2

[email protected]:~$ expr 8 / 4
2
Modulous ( % ) – Gives back remainder after division
[email protected]:~$ echo $(( 9 % 4 ))
1

[email protected]:~$ expr 9 % 4 
1
Exponentiation ( ** ) – Takes power of a number
[email protected]:~$ echo $(( 2 ** 8 ))
8
Using variables

Now let’s see how we store our result in a variable. Heads up! This post follows our Variables in Bash/Shell Scripting post; you may want to read it before continuing.

Below is an example that stores the arithmetic result in a variable using backticks or using double brackets.

You can store the result using backticks ( ` ):

var=`expr 3 + 8`

Or, you can store your result using double brackets:

var=$(( 3 + 8 ))

Let’s understand these operators a little better with the help of variables in the script. See script.sh below.

#!/bin/bash
var=`expr 3 \* 4`
echo $var

var2=$(( 3 * 5 ))
echo $var2	

num=12
num2=8
var3=`expr $num + $num2`
echo $var3

We can run this script in 2 ways:

bash script.sh

Or

chmod +x script.sh
./script.sh

This script will return the following results:

12
15
20

Relational Bash Operators:

We use these operators to define some relation between the two numbers or number strings. For instance, a number can be equal to another number, and a number can be smaller than another number, and any relationship is like this.

“582” is an example of a number string. Remember, these operators do not work for strings. They only work for numbers and number strings.

Before we learn about these operators, let’s first learn how the “if” statement works. The “if” statement executes a block of code when a particular condition is true. The syntax of the “if” statement is as follows:

if Condition/s; then Statement/s; fi

Or

if Condition
then
  Statement/s
fi

Now, let’s understand relational operators with the help of a table.

-eq OR ==

Returns true if the values of two operands are equal.

[email protected]:~$ if [ 5 -eq 5 ];then echo 5; fi
5

[email protected]:~$ if ((5 == 5));then echo 5; fi
5
-ge OR >=

Returns true if the value of the 1st operand is greater than or equal to the value of the 2nd operand.

[email protected]:~$ if [ 6 -ge 5 ];then echo 6; fi
6

[email protected]:~$ if ((6 >= 5));then echo 6; fi
6
-le OR <=

Returns true if the value of the 1st operand is less than or equal to the value of the 2nd operand.

[email protected]:~$ if [ 6 -le 7 ];then echo 6; fi
6

[email protected]:~$ if ((6 <= 7));then echo 6; fi
6
-gt OR >

Returns true if the value of the 1st operand is greater than the value of the 2nd operand.

[email protected]:~$ if [ 7 -gt 6 ];then echo 7; fi 
7

[email protected]:~$ if ((7 > 6));then echo 7; fi
7
-lt OR <

Returns true if the value of the 1st operand is less than the value of the 2nd operand.

[email protected]:~$ if [ 6 -lt 7 ];then echo 6; fi 
6

[email protected]:~$ if ((6 < 7));then echo 6; fi
6
-ne OR !=

Returns true if the values of the two operands are not equal.

[email protected]:~$ if [ 7 -ne 6 ];then echo "Not Equal"; fi 
Not Equal

[email protected]:~$ if ((7 != 6));then echo "Not Equal"; fi
Not Equal

Always use a space before the first operand and after the last operand when writing expressions using square brackets [ ] as I did above.

Let’s understand these operators more with the help of variables in the shell script named script.sh

#!/bin/bash
var=20
var2=40

if [ $var2 -ge $var ]
then
    echo "$var2 is greater than $var"
fi

if (($var <= $var2))
then
    echo "$var is less than $var2"
fi

Now, run this script with a bash script.sh command, and it will produce the following results:

40 is greater than 20
20 is less than 40

Remember, you can use both types of “if” statements, single-line, or multi-line whatever you feel comfortable with. But the single-line “if” statement will save some space while the multi-line “if” statement will be easier to debug.

Now, let’s understand these operators more with the help of an if_else_script.sh script having an if-else statement.

#!/bin/bash
var=20
var2=40

# Multine-line if else statement
if [ $var -ge $var2 ]
then
    echo "$var is greater than $var2"
else
    echo "$var is lesser than $var2"  
fi

# Single-line if else statement
if (($var >= $var2)); then echo "$var is greater than $var2"; else echo "$var is lesser than $var2"; fi

When we run this script, it gives the following output:

20 is lesser than 40
20 is lesser than 40

You may also be interested in



About the Authors

Anto's editorial team loves the cloud as much as you! Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



About Anto Online

Having started his career in 1999 as a Desktop Support Engineer, Anto soon changed paths and became a developer. After several years of development experience, he transitioned into a consultant. As an enterprise application consultant for a leading SaaS software provider, Anto specializes in AWS's serverless technologies. By day, Anto focuses on helping customers leverage the power of serverless technologies. By night, he indulges his passion for cloud computing by playing with Python and trying out things that are currently beyond the scope of his work. Sometimes Anto needs help as there are not enough hours at night. So Anto relies on a team of fellow Cloud enthusiasts to help him out. Each one is a Cloud expert in their own right, and Anto takes great pride in helping them learn and grow.

View all posts by Anto Online →

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.