Note: The following material was developed by Claude Cantin of the Research Computing Support Group of the National Research Council of Canada, and is used with his permission.

test: Comparisons

A common requirement of many programs is to compare two, three, or more things together. Strings and numbers may be compared. Files are often checked for their lengths and/or existence.

All such verifications are done using variants of the test command.

The general usage of test is

test expression

If expression is true, a return code of 0 is supplied.

If expression is false, a non-zero return code is generated.


Testing/Comparing Numbers

The primitives available for comparison of numeric values are

For example:

    #!/bin/sh

    if test $# -le 5
    then
        echo Less than or equal to five parameters.
    else
        echo More than 5 parameters.
    fi
    exit 0


Verifying File Types

To test file types, a number of primitives are used

-s
checks that the file exists and is not empty.
-f
checks that the file is an ordinary file (not a directory).
-d
checks whether the file is really a directory.
-x
checks that the file is executable.
-w
checks that the file is writeable.
-r
checks that the file is readable.

An example would be where a program needs to output something to a file, but first checks that the file exists:

    #!/bin/sh
    if test ! -s arg.file
    then
        echo "arg.file is empty or does not exist."
        ls -l > arg.file
        exit
    else
        echo "File arg.file already exists."
    fi
    exit 0
Note the exclamation mark within the test sequence. The exclamation mark means ``not".


Comparing Strings

String comparisons are done using = and !=:

    #!/bin/sh
    if test $# -eq 0
    then
        echo Must provide parameters.
        exit 1
    fi
    
    while test ! $1 = "end"
    do
        echo parameter is $1
        shift
        if test $# -eq 0
        then
            echo Parameter list MUST contain the '"'end'"' string.
            exit
        fi
    done
    echo Done: I"'"ve hit the '"'end'"' string.
    exit 0
Note that the above example could have been MUCH shorter if no error checking took place.

The length of strings can also be tested using:

-z
: check if the string has zero length.
-n
: check if the string has a non-zero length.


Combining test: Expressions

Two or more test expressions may be combined, using the -o (or) and/or the -a (and) attributes:

    #!/bin/sh
    if test $# -eq 0
    then
        echo Must provide parameters.
        exit 1
    fi

    if test $# -gt 2 -a $# -lt 5
    then
        echo There are 3 or 4 parameters.
    fi

    if test $# -ge 1 -a $# -lt 3 
    then
        echo There are 1 or 2 parameters.
    fi
    exit 0

Note that -a has precedence over -o.