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.
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.
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
To test file types, a number of primitives are used
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".
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:
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.