Back to the command reference

test

ShellAdvanced In simulator In real Linux

Evaluate a condition (also written [ ... ])

Name: test; [ is another name for it

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

test evaluates a conditional expression and exits 0 if it holds, 1 otherwise. [ is the same command with a required closing ], which is why the spaces inside the brackets matter.

It tests files (-f, -d, -r …), strings (=, !=, -z, -n) and integers (-eq, -lt …). In bash, [[ ]] is usually preferred.

Syntax

test EXPRESSION

Common options

-eThe file exists (any kind)
-fFile exists and is a regular file
-dDirectory exists
-LIt is a symbolic link
-sThe file exists and is not empty
-r / -w / -xYou may read / write / execute it
-nt / -otNewer / older than another file: [ a -nt b ]
-zString is empty
-nThe string is not empty
= / !=Strings equal / not equal (spaces around =)
-eq -lt -gtInteger comparison: equal, less, greater
! / -a / -oNot / and / or

Examples

  • $ test -f config.yml && echo found

    Print found if the file exists

    Explain
  • $ [ -d backup ] || mkdir backup

    Create the directory if missing

    Explain
  • $ [ "$n" -gt 10 ] && echo big

    Compare numbers

    Explain

Related