Sem 3‎ > ‎OS (Unix) LAB‎ > ‎

D6: Operators

posted Oct 9, 2011, 5:59 AM by Neil Mathew   [ updated Oct 9, 2011, 6:05 AM ]





Relational Operators

Bourne Shell supports following relational operators which are specific to numberic values. These operators would not work for string values unless their value is numerics.

For example, following operators would work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty".

Assume variable a holds 10 and variable b holds 20 then:

Show Examples

OperatorDescriptionExample
-eqChecks if the value of two operands are equal or not, if yes then condition becomes true.[ $a -eq $b ] is not true.
-neChecks if the value of two operands are equal or not, if values are not equal then condition becomes true.[ $a -ne $b ] is true.
-gtChecks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.[ $a -gt $b ] is not true.
-ltChecks if the value of left operand is less than the value of right operand, if yes then condition becomes true.[ $a -lt $b ] is true.
-geChecks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.[ $a -ge $b ] is not true.
-leChecks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.[ $a -le $b ] is true.

It is very important to note here that all the conditional expressions would be put inside square braces with one spaces around them, for example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.




Logical Operators 

These seem to work perfectly on my side . 


&&Logical "and"
||Logical "or"

! <- Test this too

But, according to the net, we should use:


OperatorDescriptionExample
!This is logical negation. This inverts a true condition into false and vice versa.[ ! false ] is true.
-oThis is logical OR. If one of the operands is true then condition would be true.[ $a -lt 20 -o $b -gt 100 ] is true.
-aThis is logical AND. If both the operands are true then condition would be true otherwise it would be false.[ $a -lt 20 -a $b -gt 100 ] is false.


Arithmatic Operators


#!/bin/sh

a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a is equal to b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi

This would produce following result:

a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a is not equal to b

Comments