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 |
---|---|
|
This stands for equal to |
|
This stands for not equal to |
|
This stands for greater than |
|
This stands for less than |
|
This stands for greater than or equal to |
|
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:
#!/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"
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.