UNIX and Linux Shell Script Test Command

The Test command is often used in control flows. It returns 0 if something is true, and non-zero if it is false. Statements such as the "if" command are a great place to make use of this.

Common Test Cases

test returns true in the following cases:
test ss is not a null string
test -n stringstring is nonzero
test sting1 = string2the two strings are equal
test sting1 != string2the two strings are not equal
test integer1 -eq integer2the integers are equal
test integer1 -ge integer2integer1 is greater or equal to integer2
test integer1 -gt integer2integer1 is greater than integer2
test integer1 -le integer2integer1 is less than or equal to integer2
test integer1 -lt integer2integer1 less than integer2
test integer1 -ne integer2integer1 is not equal to integer2
test -f fileif the file exists and is not a directory
test -r filethe file is readable
test -w file the file is writable
test -d dir dir is a directory

An Example of Test

Here, we simply check to see if java exists in /usr/bin using the "test" command.


if test -f /usr/bin/java
then
	echo "Java exists in /usr/bin/"
fi

Using Square brackets

Square brackets can be used to replace the test command in most command shells. Here is an example of this. Note that the spaces between the brackets and the test operation are vital here.


if [ -f /usr/bin/java ]
then
	echo "Java exists in /usr/bin/"
fi

Testing strings

When testing strings in shell scripts be aware that a null string may cause the shell interpreter to error.

For example:
[ string1 == string2 ]
will be fine as long as neither string is null, but if one or both evaluate to null, then the shell command interpreter will throw an error. Put quotes around your string to avoid this error condition:
[ "string1" == "string2" ]

Using Double Square brackets

With some shell command interpreters such as the Korn Shell and Bash you can also use double square brackets. The test operators used for single brackets are the most standard, whereas the double square bracket test operators behave in a slightly different way.

For example:
[[ string1 == string2 ]]
is valid in in Korn shell, and checks to see if the value of string1 equals string2.

If you were to write this using single brackets:

[ string1 == string2 ]This is wrong and some command shells would complain
[ string1 = string2 ]Better. This would work unless one string was null
[ "string1" = "string2" ]Even better! This should work with all Bourne derived command shells