Using the test command to test conditions

Before discussing the various control structures, it is useful to talk about ways to test for various conditions. The test command tests to see whether something is true.

Examining the nature of a file

Table 1 lists the test commands that you can use to determine the nature of a file.
Table 1. Using the test command to examine the nature of a file
Syntax of the test command Questions asked
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?

Comparing the age of two files

Table 2 lists the test commands that you can use to compare the age of two files.
Table 2. Using the test command to compare the age of two files
Syntax of the test command Questions asked
test file1 -ot file2 Is file1 older than file2?
test file1 -nt file2 Is file1 newer than file2?

Comparing the values of two numbers

Table 3 lists the test commands that you can use to compare the values of two numbers.
Table 3. Using the test command to compare the values of two numbers
Syntax of the test command Questions asked
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?

Comparing two strings

Table 4 lists the test commands that you can use to compare two strings.
Table 4. Using the test command to compare two strings
Syntax of the test command Questions asked
test str1 = str2 Is str1 equal to str2?
test str1 != str2 Is str1 not equal to str2?

Testing whether strings are empty

Table 5 lists the test commands that you can use to determine whether strings are empty.
Table 5. Using the test command to test whether strings are empty
Syntax of the test command Questions asked
test -z string Is string empty?
test -n string Is string not empty?

Any of these tests will also work if you put 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 bracket [[test_expr]] syntax is also supported. The double bracket ([[ ]]) also supports additional tests over the test command, and there are some subtle differences between the tests (for example, string equal versus 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 whether 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.