← All commands
THE COMMAND REFERENCE

test

Check files, strings and numbers, and report with the exit status.

Last updated

macOS / Apple

Implementation-level reference; examples are not certified for every installed version.

Overview

test evaluates a condition and reports the result with its exit status: 0 for true, 1 for false. It checks whether a file exists or is a folder, whether a string is empty or equal to another, and how two numbers compare. The same command is also written [ condition ], with the closing bracket as the last argument; that is what if [ -f file ] uses.

Background

The test command, also written [, is how shell scripts have always asked questions about files and values. Today the name covers the Bash builtin, GNU test, the test that macOS ships, and the test applet in BusyBox. They agree on the file tests -e, -f, -d, -s, -r, the string tests -z, -n, = and the number tests -eq, -lt, -gt.

Examples

Check that a folder exists:

test -d logs && echo dir

Check that a regular file exists:

test -f notes.txt && echo file

Check that something does not exist:

test -e missing.txt || echo missing

Check that a file is not empty:

test -s notes.txt && echo nonempty

Check that a string is empty:

test -z "" && echo empty

Compare strings with a single equals sign:

test "a" = "a" && echo equal

Compare numbers with -lt:

test 3 -lt 5 && echo yes

Negate a test with !:

test ! -e missing.txt && echo not there

Write the same test with brackets; the spaces inside them are required:

[ -n "x" ] && echo set

Options

-e
True if the path exists, whatever its type.

-f
True if the path is a regular file.

-d
True if the path is a folder.

-s
True if the file exists and is not empty.

-z
True if the string is empty.

-n
True if the string is not empty.

Common mistakes

Spaces matter: [ -f file ] works, and [-f file] is an error. Quote variables, as in test "$a" = "$b", or an empty value shifts the arguments. Use = for strings and -eq for numbers: [ 10 = 10.0 ] is false and [ 10 -eq 10 ] is true. Do not use -a and -o to combine tests, because they are ambiguous; chain several test commands with && and ||. The Bash [[ ... ]] is a different, shell-only keyword and is not covered here.

Portability

Only the tests listed above are in the Common examples. == for strings, -a and -o, -nt, -ot and -ef are common but not in POSIX. The examples use test; the [ form runs the shell builtin in the executable checks. The Common examples were executed on Bash 5.2, GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).

About macOS test

This is the test in the system folders of macOS. It follows the BSD implementation, and is the executable that runs when you call it by path, as in /bin/test.

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.