In Bash shell scripting we can perform comparison of the numbers. To perform bash compare numbers operation you need to use “test” condition within if else loop. This Post will quickly tell you how to bash compare numbers.
Operators for bash compare numbers
Operator | Meaning | Example |
---|---|---|
-eq | bash compare numbers for equality Returns 0 if its equal | if [ $a -eq $b ] then |
-ge | bash compare numbers if its greater than or equal . Result returns 0 if it’s greater than or equal | if [ $a -ge $b ] then |
-gt | bash compare numbers if its greater. | if [ $a -gt $b ] then |
-le | bash compare numbers if its less than or equal. | if [ $a -le $b ] then |
-lt | bash compare numbers if its less. | if [ $a -lt $b ] then |
-ne | bash compare numbers if its not equal or not. | if [ $a -ne $b ] then |
Detail examples of bash compare numbers operators:
1. -eq operator
This bash compare numbers operator will check the values are equal or not. If its equal it return value 0.
[root@rhel1 ~]# cat test.sh #!/bin/bash echo "enter value of a variable" read a echo "enter value of b variable" read b if [ $a -eq $b ] then echo "Returned value is:: $?" echo "a and b are equal" else echo "Returned value is:: $?" echo "a and b are not equal" fi [root@rhel1 ~]#
Execution:
[root@rhel1 ~]# sh test.sh enter value of a variable 2 enter value of b variable 3 Returned value is:: 1 a and b are not equal [root@rhel1 ~]# sh test.sh enter value of a variable 2 enter value of b variable 2 Returned value is:: 0 a and b are equal [root@rhel1 ~]#
In the above example we taken 2 and 3 for the first time at that time system returns value 1, however when we taken same values for a and b variable system returns value zero.
2. -ge operator
This bash compare numbers operator will check the values for greater than or equal . If its greater than or equal then it return value 0.
[root@rhel1 ~]# cat test1.sh #!/bin/bash #program for -ge comparing echo "enter value of a variable" read a echo "enter value of b variable" read b if [ $a -ge $b ] then echo "Returned value is:: $?" echo "a is greater than or equal to b" else echo "Returned value is:: $?" echo "a is not greater than or equal to b" fi [root@rhel1 ~]#
Output of execution:
3. -gt operator
This bash compare numbers operator will check the values for greater than. If it’s greater than, then it return value 0.
Leave a Reply