Bash Scripting: Operators

Using operators in a Bash script is how you determine whether a condition is true or not. And testing for conditions is how we program a Bash script to be dynamic by giving it the ability to respond differently depending on a scenario.

Creating conditionals is why it is essential to know the various Bash operators. Operators let us test things like arithmetic functions, compare strings, check if a file exists, and a lot more.

In this tutorial, you will learn about all of the operators that can be used in a Bash script on a Linux system. We will go over examples so you can learn how to use each type of operator in real context.

In this tutorial you will learn:

  • How to use arithmetic comparison operators
  • How to use arithmetic operators
  • How to use string comparison operators
  • How to use Bash file testing operators
  • How to use boolean operators
An example of using an operator inside of a Bash script on Linux
An example of using an operator inside of a Bash script on Linux
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Bash Scripting: Arithmetic Comparison Operators




Let’s first go over arithmetic comparison operators. These are simple to understand and are usually used on two numbers to determine if a certain condition is true or false. Here is an example.

#!/bin/bash

# declare integers
NUM1=2
NUM2=1

if [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
else 
	echo "Values are NOT equal"
fi

In the script above, our if statement uses the -eq operator to determine if two integers are equal to each other. Dependng on the answer, the if statement will either proceed with its first or second clause.

Here is a list of other arithmetic operators that you can use in your Bash script.

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=

Note that the operators in the left column will work with single brackets [ ] or double brackets [[ ]], whereas the operators in the right column will work only with double brackets.

Bash Scripting: Arithmetic Operators

Arithmetic operators in Bash give us the ability to do things like addition, subtraction, multiplication, division, and other basic arithmetic inside of a Bash script.

#!/bin/bash
 
echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION 

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ] 
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result

The script above serves as an example of how to use all of the arithmetic calculation operators in Bash. There are also increment (++) and decrement (--) operators, as seen in the while loop below.

#!/bin/bash

i=5

while [ $i -gt 0 ]
do
   echo Countdown ends in $i...
   ((i--))
   sleep 1
done

echo Countdown is over!




This script using the decrement operator to continually reduce the value of the $i variable with each successive iteration through the while loop.

Bash Scripting: String Comparison Operators

We can use string comparison operators to determine if a string is empty or not, and to check if a string is equal, less, or greater in length to another string.

#!/bin/bash

#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"

if [ $S1 = $S2 ]; then
	echo "Both Strings are equal"
else 
	echo "Strings are NOT equal"
fi

The script above has an if statement that uses the = string comparison operator to determine if two strings are equal in length or not.

Here is a list of other string comparison operators that you can use in your Bash script.

= equal
!= not equal
< less then
> greater then
-n s1 string s1 is not empty
-z s1 string s1 is empty

Bash Scripting: Bash File Testing Operators

In Bash, we can test to see different characteristics about a file or directory. The following script will check to see if a file exists or not.

#!/bin/bash

file="./file"

if [ -e $file ]; then
	echo "File exists"
else 
	echo "File does not exist"
fi

The script above uses the -e Bash file testing operator to dermine if $file exists or not. Depending on the answer, either the first or second clause of the if statement will be executed.

Here is a list of other Bash file testing operators that you can use in your Bash script.

-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable

Bash Scripting: Boolean Operators

Boolean operators include and &&, or || and not equal to !. These operators allow us to test if two or more conditions are true or not.



#!/bin/bash

i=10

if [ $i -ge 5 ] && [ $i -le 15 ]; then
    echo "value is between 5 and 15."
fi

The script above uses the && operator to test if two conditions are true (if variable $i is between numbers 5 and 15). If they are, then the echo command is executed.

Closing Thoughts

In this tutorial, we saw how to use various types of operators in Bash scripting on Linux. These operators allow us to perform basic arithmetic or to test for certain conditions. Operators are essential in Bash scripts that have more than one set of instructions that could be executed under different conditions.



Comments and Discussions
Linux Forum