Shell Test Flags

Flags you can use with the test command, e.g.

if test -e /path/to/file; then
    echo "file exists"
fi

File Tests

-d file True if file exists and is a directory
-e file True if file exists
-f file True if file exists and is a regular file
-L file True if file exists and is a symlink
-s file True if file exists and has size greater than zero
-x file True if file exists and is executable

String Tests

-n string True if string has non-zero length
-z string True if string has zero length
string1 = string2 True if the strings are identical
string1 != string2 True if the strings are not identical

Numerical Tests

int1 -eq int2 True if the integers are equal
int1 -ge int2 True if int1 is greater than or equal to int2
int1 -gt int2 True if int1 is greater than int2
int1 -le int2 True if int1 is less than or equal to int2
int1 -lt int2 True if int1 is less than int2
int1 -ne int2 True if the integers are not equal

Operators

The negation operator is !, e.g.

if test ! -e /path/to/file; then
    echo "file does not exist"
fi

The test command may support -a and -o operators for boolean AND and OR, but these are not portable. For boolean logic, use multiple invocations of the test command with the shell operators && and ||, e.g.

if test -e file1 && test -e file2; then
    echo "both files exist"
fi

if test -e file1 || test -e file2; then
    echo "at least one file exists"
fi

Aliases

The bracket command, [, is an alias for test, e.g.

if [ -e /path/to/file ]; then
    echo "file exists"
fi

The trailing bracket ] must be included and both brackets must be offset by spaces.

Although often seen in the wild, this bracket alias manages to be both useless and error-prone. There's never a reason to use it.