Comparison
Unlike other scripting language shell script has provided different methods to compare string and numbers.
1. Numeric Comparison
Syntax : test Number1 option Number2
Test command will return the true of false based on the opration performed between two numbers
Different options are as below:
· -ne means Not Equal to
· -lt means Less Then
· -le means Less Then or Equal to
· -gt means Greater Then
· -ge means Greater Then or Equal to
Example:
a=10
b=20
test $a –eq $b # will return False
test $a –lt $b # will return True
- String Compression
String comparison done with the simple mathematical operator
Syntax: test string1 option string2 or test option string
Different options are as below:
· = = means Equal to
· != means Not Equal to
· -n means Not NULL ( unary operator )
· -z means NULL ( unary operator )
Example:
Test “Gaurang” == “Gaurang” # this will return True A=”string “
Test -z “$A” # will Return false as A is not NULL
Note: Remember if you are compring strings and the strings are assigned in some variables you need to put that variables in the double quotes ( “$str” ), other wise it will give you error.
Computation
In the shell script you can’t directly add the two numbers as follows
A=1 + 1 # this will gives you error
There is a special command called expr that is used for the normal integer computation.
Syntax: expr num1 operator num2
Example:
a=2
b=3
c=`expr $a + $b`
echo $c # will print 5, summation of 2 and 3
c= `expr $b / $a`
echo $c #will print 1, as expr returns only integer value
c= `expr $a * $b` # will gives you error,
# asterisk ( * ) has some other special meaning
c=`expr $a \* $b` # correct way to multiply the value
echo $c # will print 6
1 comment:
I tried comparing strings but getting return 0, while following your linux tutorials at
http://www.codeandcommand.com/linux/linux-shell-scripting/how-to-install-mod-page-speed-in-centos.html
Post a Comment