test

Linux · Terminal · reference only

What it does

Evaluates a condition about files, strings or numbers and returns an exit status: 0 if true and 1 if false. [ ... ] is its equivalent form.

Syntax

test expresión
[ expresión ]

Options and parameters

  • -f fichero

    True if it exists and is a regular file.

  • -d ruta

    True if it exists and is a directory.

  • -e ruta

    True if it exists, of any type.

  • -s fichero

    True if it exists and is not empty.

  • -z cadena

    True if the string is empty.

  • -n cadena

    True if the string is not empty.

  • a = b | a != b

    Compares strings: equal or different.

  • -eq -ne -lt -gt -le -ge

    Compare numbers: equal, not equal, less, greater, less or equal, greater or equal.

Usage examples

  • test -f notas.txt && echo existe

    Prints existe only if notas.txt is a file.

  • [ -d /tmp ] && echo "es un directorio"

    Uses the bracket form to check a directory.

  • test "$USER" = root || echo "no eres root"

    Warns when the current user is not root.

  • [ 5 -gt 3 ] && echo mayor

    Compares two numbers; it prints mayor because 5 is greater than 3.

Notes and common mistakes

  • In the bracket form you must leave a space inside [ and ].
  • Quote variables so an empty variable does not break the expression.
  • It prints nothing: the result is read in $? or with && and ||.

Related commands