I Love Tips

Nice Tips & Tricks made easy

Testing Conditions in Shell Programming

Posted by Rajkiran Ghanta on May 18, 2008

In the shell programming, conditional expressions are used for performing tests by
- evaluating and comparing integers or strings
- testing file attributes

Testing Conditional expressions is done by using the following three different forms of syntax.
test expression
[ expression ]
[[ expression ]]

These expressions will return an exit status of 0 for true and 1 for false. It is preferrable to use [[ ]] command, as it will result in fewer syntax errors.

Example :
To compare two integers, by checking if one is less than the other with one of the following :
[[ $a gt $b ]]
[ $a gt $b ]
test $a gt $b

You can also combine two or more expressions (aka. compound expressions) using the following operators
- Double ampersand, && ( which means “AND” )
- Double Pipe, || (which means “OR”)

Example :
the syntax for for compound expressions using || is :
[[ expression1 || expression2 ]]

If you would like to test student’s subject mark with minimum required mark and print pass if either of the subject is more than the required score, the sample code would be

$[[ $SubjectA > $ReqScore || $SubjectB > $ReqScore ]] && print “PASS”

[[ .... ]] syntax can also be used for the following tests :
To test variables with string operators
-z true if length is zero
-n will be true if the string is not zero
-o will be true if option is set

example:
if [[ -z $StringA ]]; then
print “Length is zero”
fi

To compare one string with another string
[[ string1 = string2 ]]

Example :
[[ $Subject = "MATH A" ]] && print “Optional Subject”

To compare strings with String operators
=, !=, < , >

To test files with options
-a (file exists)
-d (file is a dir)
-f (file is regular file)
-r (file readable)
-w (file writable)
-x (file executable)
-s (file non-empty)
-u (file has userID bit set)

To compare files
[[ file1 -ef file2]] for same files
[[ file1 -nt file2]] for finding new file
[[ file1 -ot file2]] for finding older file

To compare expressions involving integers using integer operators
-eq, -ne, -le, -ge, -gt

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>