test

From NetBSD Wiki

Jump to: navigation, search

With test(1) you can perform comparisons of strings or numbers and test for file types. It will return an exit code of zero or one, depending on whether the expression evaluates to true or false, respectively.

Test is also known as "[" Note: most shells have [ builtin.

Example:

if test "foo" != "foo"; then
echo "Of course this is never printed!"
fi

More conventionally, we'd use the [ alias.

if [ "foo" = "foo" ]; then
echo "Of course this is printed!"
fi

The closing ] is for balance, it doesn't do anything functional. (but [ will complain if it doesn't encounter a matching ] ).

You can check if two strings are equal:

i="foo"
j="foo"
if [ "$i" = "$j" ]; then
echo "foo equals foo!"
fi

The other string comparison operators are: != < >

if test "aa" '<' "aaba"
then echo "aa is lexically smaller than aaba"
elif test "aa" \> "aaba"
then echo "Not reached"
fi

Note that the < and > operators must be quoted and that the well-known double equals sign for equality is not defined.

For numbers, use -eq (instead of =):

i=10
j=10
if [ $i -eq $j ]; then
echo "10 equals 10!"
fi

The other operators for numerical comparisons are: -ne -gt -lt -ge -le

A large numbers of operators (see the man page) work on filenames:

x=/dev/null
if test -r "$x"
then echo "file $x exists and is readable"
fi

Note that with -nt you can also compare the change dates of files.

Also, negation, boolean operators (and / or) and grouping with (escaped) brackets is possible.

Hints

Use (double) quotes around arguments routinely, but in particular in testing values. The list of charcters that are shell special characters is impressively large: & && ( ) ; ;; | || < > >| << >> <& >& <<- <>! (not included tilde expansion).

Using quotes also avoids some curious results:

x=""
if test -r $x
then echo "no parameter is a good parameter?"
fi
if test -r "$x"
then echo "Empty filname is rightly not readable"
fi

To test for an empty string (of zero length), use test -n or test -z:

x=""
if test -z "$x"                       
then echo String is empty
elif test -n "$x"
then echo Oops, this should not print
fi

To shield empty values by concatenation of a fixed string is bad style in any Unix shell (it was necessary in MS-DOS batch files), better use quotes correctly:

if test x$i = xok       # DO NOT USE
then echo "$i is ok, but this is bad MS DOS style"
fi
if test "$i" = "ok"     # this is Unix shell style
then echo "$i is ok"
fi

View source code (Please report any bugs or suggestions here).

Retrieved from "http://wiki.netbsd.se/test"
Personal tools