Sunday, April 12, 2009

Checking condition in shell scipt by test or [expr]

With test command or expression within bracket (for example, [expression here]) you can check whether condition is true inside shell script. If condition is true then it returns zero (0) otherwise it returns non-zero value for false.
Checking condition by test
# cat check_gt10.sh
if test $1 -gt 10
then
echo "$1 is greater than 10"
fi

# chmod +x check_gt10.sh

# ./check_gt10.sh 19
19 is greater than 10

# ./check_gt10.sh 5

Checking condition by [expression]
# vi check_gt10_2.sh
if [ $1 -gt 10 ]
then
echo "$1 is greater than 10"
fi

# chmod +x check_gt10_2.sh

# ./check_gt10_2.sh 10

# ./check_gt10_2.sh 11
11 is greater than 10

With test or [expression] you can check condition of
-integer numbers.
-file types.
-character strings

Integer Number Comparison:
Usage in shell scriptMeaningMathematical StatementsInside Shell Script
Check by test statement with if conditionCheck by [ expr ] statement with if condition
-eqis equal to3 == 4if test 3 -eq 4if [ 3 -eq 4 ]
-neis not equal to3 != 4if test 3 -ne 4if [ 3 -ne 4 ]
-ltis less than3 <>if test 3 -lt 4if [ 3 -lt 4 ]
-leis less than or equal to3 <= 4if test 3 -le 4if [ 3 -le 4 ]
-gtis greater than3 > 4if test 3 -gt 4if [ 3 -gt 4 ]
-geis greater than or equal to3 >= 4if test 3 -ge 4if [ 3 -ge 4 ]

Strings Comparison:
OperatorMeaning of the using
string1 = string2string1 is equal to string2
string1 != string2string1 is NOT equal to string2
string1string1 is NOT NULL or not defined
-n string1string1 is NOT NULL and does exist
-z string1string1 is NULL and does exist

Files Comparison:
TestMeaning of the text
-s file Non empty file
-f file Is File exist or normal file and not a directory
-d dir Is Directory exist and not a file
-w file Is writeable file
-r file Is read-only file
-x file Is file is executable

Comparison with logical operators:
Operator Meaning of using
! expressionLogical NOT
expression1 -a expression2Logical AND
expression1 -o expression2Logical OR


Related Documents

No comments:

Post a Comment