Skip to content

Bash test/conditional API

Bash test expressions — file, string and numeric comparisons used in [ ] and [[ ]] conditionals.

1 class · 8 methods

test/conditional

8 methods

Test operators for use with the [ (test) command and the more powerful [[ ]] compound command.

[ -f file ]

Returns true if file exists and is a regular file (not a directory or device).

Parameters

NameTypeDescription
filepathPath to test.

Returns

boolean (exit status)

Example

bash
if [ -f /etc/hosts ]; then
    echo "regular file exists"
fi
[ -d dir ]

Returns true if dir exists and is a directory.

Parameters

NameTypeDescription
dirpathPath to test.

Returns

boolean (exit status)

Example

bash
if [ -d /tmp ]; then
    echo "directory exists"
fi
[ -z string ]

Returns true if the length of string is zero (empty).

Parameters

NameTypeDescription
stringstringString to test.

Returns

boolean (exit status)

Example

bash
name=""
if [ -z "$name" ]; then
    echo "name is empty"
fi
[ -n string ]

Returns true if the length of string is non-zero (not empty).

Parameters

NameTypeDescription
stringstringString to test.

Returns

boolean (exit status)

Example

bash
name="hello"
if [ -n "$name" ]; then
    echo "name is set"
fi
[ str1 = str2 ]

Returns true if the two strings are equal. Use != for inequality.

Parameters

NameTypeDescription
str1stringFirst string.
str2stringSecond string.

Returns

boolean (exit status)

Example

bash
if [ "$USER" = "root" ]; then
    echo "running as root"
fi
if [ "$a" != "$b" ]; then
    echo "different"
fi
[ num1 -eq num2 ]

Returns true if the two integers are equal. Other numeric ops: -ne, -lt, -le, -gt, -ge.

Parameters

NameTypeDescription
num1integerFirst integer.
num2integerSecond integer.

Returns

boolean (exit status)

Example

bash
count=5
if [ $count -eq 5 ]; then echo "five"; fi
if [ $count -gt 3 ]; then echo "greater than 3"; fi
if [ $count -le 5 ]; then echo "less or equal 5"; fi
[ -e path ]

Returns true if path exists (any type: file, directory, symlink, etc.).

Parameters

NameTypeDescription
pathpathPath to test.

Returns

boolean (exit status)

Example

bash
if [ -e /usr/bin/python3 ]; then
    echo "python3 exists"
fi
[[ str =~ regex ]]

Returns true if str matches the extended regular expression regex. Only in [[ ]], not [ ].

Parameters

NameTypeDescription
strstringString to test.
regexregexExtended regular expression.

Returns

boolean (exit status)

Example

bash
phone="123-456-7890"
if [[ $phone =~ ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ ]]; then
    echo "valid phone"
fi
# Capture groups: ${BASH_REMATCH[1]}, etc.