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 ficheroTrue if it exists and is a regular file.
-d rutaTrue if it exists and is a directory.
-e rutaTrue if it exists, of any type.
-s ficheroTrue if it exists and is not empty.
-z cadenaTrue if the string is empty.
-n cadenaTrue if the string is not empty.
a = b | a != bCompares strings: equal or different.
-eq -ne -lt -gt -le -geCompare numbers: equal, not equal, less, greater, less or equal, greater or equal.
Usage examples
test -f notas.txt && echo existePrints 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 mayorCompares 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 ||.