Shell and environment

Command test

Check the condition in the shell script

Linux · Bash examples · commands run on the selected server

When to use test

Use test or shell bracket syntax to make conditional decisions about files and strings. Its result is an exit status used by control flow rather than a printed true-or-false value.

Syntax

test EXPRESSION

Square brackets mark optional arguments; an ellipsis means repetition. Replace example file names, user names and server addresses with your own values.

Common options and arguments

-f PATH
The path exists and is a regular file.
-d PATH
The path exists and is a directory.
-n STRING
The string is not empty.

Usage examples

Check file

if test -f ./app.conf; then printf '%s\n' 'config found'; fi

The message is printed only when the path is a regular file.

Check directory in bracket form

if [ -d ./logs ]; then printf '%s\n' 'logs found'; fi

The directory check gates the message without creating the directory.

Check for non-empty variable

if [ -n "$HOME" ]; then printf '%s\n' 'HOME is set'; fi

A nonempty home-directory value makes the string condition succeed.

Notes and limitations

  • The result is transmitted by the completion code: 0 - true, 1 - false; There is no plain text output.
  • Spaces around [ and ] are required. Enclose string variables in quotes, and for complex conditions, prefer separate test and &&/||.

Common questions and troubleshooting

Why are spaces required around brackets?

The bracket form is a command with separate arguments; the closing bracket must be its own argument. Preserve the syntax and quote variable values.

Does a successful permission test guarantee a later write?

No. State can change between checking and using a path. Attempt the operation safely and handle its actual error.

Further help

Options vary by version and distribution. Check the installed documentation with this command: help test.