9.3.25 test command (determines the value of a conditional expression)
Syntax 1
test conditional-expression
Syntax 2
[ conditional-expression ]
Syntax 3
[[ conditional-expression ]]
Description
This command determines the value of a specified conditional expression. The command evaluates the value of a conditional expression specified using conditional operators. It returns 0 if the result is true or 1 if the result is false. If you execute the test command or [ ] with conditional-expression omitted, it returns 1.
For details about conditional expressions, see 5.2 Conditionals.
Return codes
Return code |
Meaning |
---|---|
0 |
Normal termination
|
1 |
Normal termination
|
2 |
Error termination
|
Notes
Operators such as angle brackets (< and >) have special meanings as metacharacters. To use these characters in the test command, you must disable them as metacharacters.
When the square bracket format ([[ ]]) is used, neither a wildcard nor file name substitution is applied to a character string entered between the square brackets.
An example is shown below. In this example, it is assumed that files test.ash and hhh are located in the current directory.
[[ -f *est.ash ]] ... (1) [ -f *est.ash ] ... (2) test -f *est.ash ... (3) [[ -f ?(hhh) ]] ... (4) [ -f ?(hhh) ] ... (5) test -f ?(hhh) ... (6)
In lines (1) and (4), the wildcard enclosed in the square brackets ([[ ]]) is not applied. Therefore, it is interpreted that no applicable file exists, and the return code will be 1.
In lines (2), (3), (5), and (6), the wildcard is applied. Therefore, the determined result of the conditional expression becomes true, and the return code will be 0.
Even if the command syntax of this regular built-in command is invalid, it does not exit the shell that is executing the command.
Example
Determine whether the variables arg1 and arg2 have the same value.
test $arg1 -eq $arg2