Testing Conditions
The shell provides a test command for testing conditions. The test commands test expressions to see whether the expression is true, as follows:
test $age -eq 21
[ $age -eq 21 ]
The two statements are equivalent. This chapter uses the second format. A space is required before and after each square bracket. The test returns true if $age equals 21.Table 19-1 lists the options you can use to test values.Table 19-1. Options for Use When Testing Expressions
Option | Tests for | Example |
---|
= | equal text strings | [ $name = "John" ] |
!= | non equal text strings | [ $name1 != $name2 ] |
-eq | equal integers | [ $age -eq $adult ] |
-gt | integer1 is greater than integer2 | [ $age -gt 20 ] |
-ge | integer1 is greater than or equal to integer2 | [ $age -ge 21 ] |
-lt | integer1 is less than integer2 | [ $age -lt 18 ] |
-le | integer1 is less than or equal to integer2 | [ $age le 17 ] |
-ne | non equal integers | [ $age1 ne $age2 ] |
-n | string longer than 0 | [ -n $name ] |
-z | string with 0 characters | [ -z $name ] |
The test command can also be used to test file characteristics. Table 19-2 lists the most useful options for testing files.Table 19-2. Options for Use When Testing Files
Option | Tests for | Example |
---|
-nt | file1 newer than file2 | [ test1 -nt test2 ] |
-ot | file1 older than file2 | [ test1 -ot test2 ] |
-d | file exists and is a directory | [-d $dirname ] |
-f | file exists and is a regular file | [-f $filename ] |
-r | file exists and is readable | [-r $filename ] |
-s | file exists and has a size greater than 0 | [-s test2 ] |
-w | file exists and is writeable | [-w $filename ] |
-x | file exists and is executable | [-x $filename ] |
You can test for the negative of any expression by putting an exclamation mark at the beginning of the test, as follows:
[ ! $name = "Sam" ]
This condition is true if $name does not equal Sam. It can equal anything else.A condition can consist of more than one expression. The options for testing multiple expressions are:
-o (or)
-a (and)
The -o tests whether either one of the two expressions it connects is true. The -a tests whether both of the expressions it connects are true. For instance:
[ $age -le 50 -a $age -gt 30 ]
For this condition to test true, both expressions must be true. This condition tests for age 3150. You can test several conditions, as follows:
[ $ age -lt 50 -a $name = "John" -a $weight -eq 200 ]