Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Test Command

The test command (or [ ]) evaluates expressions for use in conditionals.

File Tests

TestDescription
-e fileFile exists
-f fileIs a regular file
-d fileIs a directory
-r fileIs readable
-w fileIs writable
-x fileIs executable
-s fileHas size > 0
-L fileIs a symbolic link

Examples

if [ -f "/etc/passwd" ]; then
    echo "File exists"
fi

if [ -d "$dir" ]; then
    echo "Is a directory"
fi

if [ -r "$file" ] && [ -w "$file" ]; then
    echo "Readable and writable"
fi

String Tests

TestDescription
-z stringString is empty
-n stringString is not empty
s1 = s2Strings are equal
s1 != s2Strings are not equal

Examples

if [ -z "$var" ]; then
    echo "Variable is empty"
fi

if [ "$USER" = "root" ]; then
    echo "Running as root"
fi

if [ "$a" != "$b" ]; then
    echo "Strings differ"
fi

Numeric Tests

TestDescription
n1 -eq n2Equal
n1 -ne n2Not equal
n1 -lt n2Less than
n1 -le n2Less than or equal
n1 -gt n2Greater than
n1 -ge n2Greater than or equal

Examples

if [ $count -eq 0 ]; then
    echo "Count is zero"
fi

if [ $x -lt 10 ]; then
    echo "x is less than 10"
fi

if [ $a -ge $b ]; then
    echo "a >= b"
fi

Logical Operators

OperatorDescription
! exprNOT
expr -a exprAND
expr -o exprOR

Examples

# NOT
if [ ! -f "$file" ]; then
    echo "File not found"
fi

# AND
if [ -f "$file" -a -r "$file" ]; then
    echo "File exists and is readable"
fi

# OR
if [ -z "$a" -o -z "$b" ]; then
    echo "At least one is empty"
fi

Combining with && and ||

# Preferred over -a and -o
if [ -f "$file" ] && [ -r "$file" ]; then
    echo "File exists and readable"
fi

if [ -z "$a" ] || [ -z "$b" ]; then
    echo "At least one is empty"
fi

Common Patterns

Check File Exists

if [ -f "$config" ]; then
    source "$config"
fi

Check Directory

if [ ! -d "$dir" ]; then
    mkdir -p "$dir"
fi

Validate Arguments

if [ $# -eq 0 ]; then
    echo "Usage: $0 file" >&2
    exit 1
fi

Compare Strings

if [ "$answer" = "yes" ]; then
    proceed
fi

Numeric Comparison

if [ $count -gt 100 ]; then
    echo "Too many items"
fi

Important Notes

Spaces Required

# Wrong
if [-f "$file"]; then

# Correct
if [ -f "$file" ]; then

Quote Variables

# Wrong (breaks if file has spaces)
if [ -f $file ]; then

# Correct
if [ -f "$file" ]; then

= vs ==

In POSIX shell, use = for string comparison:

# POSIX compliant
if [ "$a" = "$b" ]; then

# Also works but less portable
if [ "$a" == "$b" ]; then