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.
|test s||s is not a null string|
|test -n string||string is nonzero|
|test sting1 = string2||the two strings are equal|
|test sting1 != string2||the two strings are not equal|
|test integer1 -eq integer2||the integers are equal|
|test integer1 -ge integer2||integer1 is greater or equal to integer2|
|test integer1 -gt integer2||integer1 is greater than integer2|
|test integer1 -le integer2||integer1 is less than or equal to integer2|
|test integer1 -lt integer2||integer1 less than integer2|
|test integer1 -ne integer2||integer1 is not equal to integer2|
|test -f file||if the file exists and is not a directory|
|test -r file||the file is readable|
|test -w file||the file is writable|
|test -d dir||dir is a directory|
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
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
When testing strings in shell scripts be aware that a null string may cause the shell interpreter to error.
[ 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" ]
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.
[[ 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|