z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Using test to test conditions

z/OS UNIX System Services User's Guide
SA23-2279-00

Before discussing the various control structures, it is useful to talk about ways to test for various conditions.

The test command tests to see if something is true. Here are some ways it can be used:

Table 1. Uses for the test command
Examine the nature of a file  
test -d pathname Is pathname a directory?
test -f pathname Is pathname a file?
test -r pathname Is pathname readable?
test -w pathname Is pathname writable?
Compare the age of two files  
test file1 -ot file2 Is file1 older than file2?
test file1 -nt file2 Is file1 newer than file2?
Compare the values of numbers A and B  
test A -eq B Is A equal to B?
test A -ne B Is A not equal to B?
test A -gt B Is A greater than B?
test A -lt B Is A less than B?
test A -ge B Is A greater than or equal to B?
test A -le B Is A less than or equal to B?
Compare two strings str1 and str2  
test str1 = str2 Is str1 equal to str2?
test str1 != str2 Is str1 not equal to str2?
Test whether strings are empty  
test -z string Is string empty?
test -n string Is string not empty?

Any of these tests will also work if you put square brackets ([ ]) around the condition instead of using the test command. For example, test 1 -eq 1 is the equivalent of [ 1 -eq 1 ].

The double square bracket [[test_expr]] syntax is also supported. The double square bracket ([[ ]]) also supports additional tests over the test command, and there are some subtle differences between the tests (for example, string equal vs. pattern matching).

The result of test is either true or false. test returns a status of 0 if the test turns out to be true and a status of 1 if the test turns out to be false.

You can use –n to check if a variable has been defined. For example:
test -n "$HOME"
is true if HOME exists, and false if you have not created a HOME variable.
You can use ! to indicate logical negation;
test ! expression
returns false if expression is true, and returns true if expression is false. For example:
test ! -d pathname
is true if pathname is not a directory, and false otherwise.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014