Validating parameters using conditional statements

Variables can be tested and compared against other variables when using a variable as a number.

Here is a list of some of the operators that can be used:

Operator

Description

-eq

This stands for equal to

-ne

This stands for not equal to

-gt

This stands for greater than

-lt

This stands for less than

-ge

This stands for greater than or equal to

-le

This stands for less than or equal to

!

This stands for the negation operator

Let's take a look at this in our next example script:

Chapter 2 - Script 2

#!/bin/sh
#
# 6/13/2017
#
echo "script2"

# Numeric variables
a=100
b=100
c=200
d=300

echo a=$a b=$b c=$c d=$d     # display the values

# Conditional tests
if [ $a -eq $b ] ; then
 echo a equals b
fi

if [ $a -ne $b ] ; then
 echo a does not equal b
fi

if [ $a -gt $c ] ; then
 echo a is greater than c
fi

if [ $a -lt $c ] ; then
 echo a is less than c
fi

if [ $a -ge $d ] ; then
 echo a is greater than or equal to d
fi

if [ $a -le $d ] ; then
 echo a is less than or equal to d
fi

echo Showing the negation operator:
if [ ! $a -eq $b ] ; then
 echo Clause 1
else
 echo Clause 2
fi
echo "End of script2"

And the output is as follows:

Chapter 2 - Script 2

To help understand this chapter run the script on your system. Try changing the values of the variables to see how it affects the output.

We saw the negation operator in Chapter 1, Getting Started with Shell Scripting when we were looking at files. As a reminder, it negates the expression. You could also say it does the opposite of what the original statement means.

Consider the following example:

a=1
b=1
if [ $a -eq $b ] ; then
  echo Clause 1
else
  echo Clause 2
fi

When this script is run it will display Clause 1. Now consider this:

a=1
b=1
if [ ! $a -eq $b ] ; then    # negation
  echo Clause 1
else
  echo Clause 2
fi

Because of the negation operator it will now display Clause 2. Try it on your system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset