The test statement tests a given condition.It returns 1 if the condidion is false and returns 0 if the condition is true. IT uses certain operators, known as test operations, for comparison. For example, -eq is used for "equal to", -gt for "greater than" etc. Some of thes test operators are listed given below.
Let us study the following command sequence:
a = 10;
b = 20;
test $b -gt $a
echo $?
#20 is greater than 10
test $a -eq $b
echo $?
#20 is not equal equal to 10
Note the use of test in the above sequesnce. These should be spaces on either side of the test operators. We have used $? to find out the result of the test command and its values conveyed whether the previous command returned tru (0) or false (1).
The test word can be replaced by used of [ ] enclosing the condidion within brackerts as follows:
a = 10;
b = 20;
[ $b -gt $a ]
echo $?
# 20 is greater than 10
[ $a -eq $b ]
echo $?
# 20 is not equal to 10
Note that there must be spaces on either side of [ and ].
Operator Implies
-eq equal to
-ne not equal to
-gt greater than
-lt less than
-ge greater than or equal to
-le less than or equal to
-n str string str is not a null string
str same as above
-z str string str is a null string
str1= str2 string str1 is equal to str2
str1 ! = str2 string str1 is not equal to str2
if construct often uses test statements as condition. For example, the following script-segment:
a =10;
b = 20;
if test $b -gt $a
then
echo "b is greater than a"
else
echo "b is not greater than a"
fi
0 Comments:
Post a Comment