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

For numbers, don't use =, but use -eq:

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

There are also < and -lt, > and -gt, != and -ne for less than, greater than and not equal, respectively. Warning: Quote special characters like > and < from the shell! For numbers, you can also check if they are less than or equal with -le and if they are greater than or equal with -ge.

The manpage covers many more switches, including test on existance and types of files, grouping and negating expressions.

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

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