test/conditional
8 methodsTest 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
| Name | Type | Description |
|---|---|---|
| file | path | Path to test. |
Returns
boolean (exit status)
Example
if [ -f /etc/hosts ]; then
echo "regular file exists"
fi[ -d dir ]Returns true if dir exists and is a directory.
Parameters
| Name | Type | Description |
|---|---|---|
| dir | path | Path to test. |
Returns
boolean (exit status)
Example
if [ -d /tmp ]; then
echo "directory exists"
fi[ -z string ]Returns true if the length of string is zero (empty).
Parameters
| Name | Type | Description |
|---|---|---|
| string | string | String to test. |
Returns
boolean (exit status)
Example
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
| Name | Type | Description |
|---|---|---|
| string | string | String to test. |
Returns
boolean (exit status)
Example
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
| Name | Type | Description |
|---|---|---|
| str1 | string | First string. |
| str2 | string | Second string. |
Returns
boolean (exit status)
Example
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
| Name | Type | Description |
|---|---|---|
| num1 | integer | First integer. |
| num2 | integer | Second integer. |
Returns
boolean (exit status)
Example
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
| Name | Type | Description |
|---|---|---|
| path | path | Path to test. |
Returns
boolean (exit status)
Example
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
| Name | Type | Description |
|---|---|---|
| str | string | String to test. |
| regex | regex | Extended regular expression. |
Returns
boolean (exit status)
Example
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.