Other meanings of test
Computing
In Unix-like operating systems, the test command (also known as [) is a utility that evaluates conditional expressions and returns an exit status indicating whether the expression is true or false. It is a fundamental tool in shell scripting, used for file attribute checks, string comparisons, and arithmetic comparisons.
The test command evaluates an expression and returns an exit status of 0 (true) or 1 (false). It is often used in shell scripts within if, while, and until constructs. The command has two forms: test expression and the equivalent [ expression ] (with a closing bracket).1 The latter form is more common in scripts, but requires a space after the opening bracket and before the closing bracket.
The test command first appeared in Unix V1 (1971) as a way to test file attributes and string comparisons. It was later standardized by POSIX (IEEE 1003.1) and the Single UNIX Specification, which define its behavior and options. The [ alias is implemented as a built-in in most shells (e.g., bash, zsh) but also exists as an external executable in some systems.
Typical uses include checking if a file exists (-e), if it is a regular file (-f), if it is readable (-r), comparing strings (=, !=, -z for empty), and comparing integers (-eq, -ne, -lt, -le, -gt, -ge).1 For example, [ -f "/etc/passwd" ] returns true if the file exists and is a regular file.
One lesser-known fact is that the [ command is actually a synonym for test, but it requires a final argument of ]; this is why the syntax is [ ... ].2 Another is that in some shells, test is a built-in, but the external version still exists in /usr/bin/test. Additionally, the [[ keyword in bash and zsh is an enhanced version that supports pattern matching and regular expressions, but it is not POSIX-compliant.3 The test command also has a rarely used -a (logical AND) and -o (logical OR) for combining expressions, though these are considered obsolete and are not recommended for new scripts.
When writing portable shell scripts, it is important to rely on POSIX features of test. Some implementations may differ in handling of empty strings or unset variables; for example, [ "$var" = "" ] is safer than [ -z "$var" ] in some edge cases.4 Also, the -a and -o operators are ambiguous and can cause issues; using multiple test commands with && or || is preferred.
The test command is a cornerstone of shell scripting, often used implicitly in every if statement.
Served from cache
Help improve the encyclopedia. Reports go straight to the site manager.