Linux test Command

Linux 命令大全Linux Command Encyclopedia


testIt is a built-in command in the Linux/Unix system used for conditional evaluation, mainly used for various tests and comparison operations in shell scripts. It can check file attributes, compare strings and numeric values, and is an indispensable tool for writing shell scripts.


Basic Syntax

test EXPRESSION
# 或者使用方括号格式(更常用)
[ EXPRESSION ]

Note: When using the bracket format, there must be spaces between the expression and the brackets, i.e.,[空格EXPRESSION空格]


Main Function Categories

1. File Testing

Checks various attributes of files or directories:

Expression Meaning
-e 文件 Whether the file exists
-f 文件 Is a regular file (not a directory or device file)
-d 文件 Is a directory
-s 文件 File size is not empty
-r 文件 File is readable
-w 文件 File is writable
-x 文件 File is executable
-L 文件 File is a symbolic link

Example:

Examples

if [ -f "/etc/passwd" ]; then
    echo "This is a regular file"
fi

2. String Comparison

Compares the relationship between two strings:

Expression Meaning
-z "字符串" String length is 0
-n "字符串" String length is not 0
"串1" = "串2" Strings are equal
"串1" != "串2" Strings are not equal

Example:

Examples

read -p "Enter username: " username
if [ -z "$username" ]; then
    echo "Username cannot be empty"
fi

3. Numeric Comparison

Compares the relationship between two integers:

Expression Meaning
n1 -eq n2 Equal
n1 -ne n2 Not equal
n1 -gt n2 Greater than
n1 -ge n2 Greater than or equal to
n1 -lt n2 Less than
n1 -le n2 Less than or equal to

Example:

Examples

if [ $(id -u) -eq 0 ]; then
    echo "Currently the root user"
fi

4. Logical Operators

Combines multiple test conditions:

Operator Meaning Example
! Logical NOT [ ! -f file ]
-a Logical AND [ -f file -a -r file ]
-o Logical OR [ -d dir -o -f file ]

Modern recommended syntax(using&&and||):

Examples

[ -f file ] && [ -r file ]  # File exists and is readable
[ -d dir ] || [ -f file ]   # Is a directory or a file

Advanced Usage

1. Compound Condition Evaluation

Examples

if [ -f "/etc/passwd" -a -r "/etc/passwd" ]; then
    echo "File exists and is readable"
fi

2. Combining with if Statements

Examples

if [ "$1" = "start" ]; then
    echo "Starting service..."
elif [ "$1" = "stop" ]; then
    echo "Stopping service..."
else
    echo "Invalid parameter"
fi

3. Using in Variable Assignment

Examples

[ -z "$PATH" ] && PATH="/usr/bin:/bin"  # Set a default value if PATH is empty

Common Errors and Cautions

Space Issues:

Examples

[ "$var" = "value" ]  # Correct
[ "$var"="value" ]    # Incorrect, missing space

Quoting String Variables:

Examples

[ -n "$var" ]  # Correct, prevents errors when the variable is empty
[ -n $var ]    # Errors when $var is empty

Numeric Comparison vs String Comparison:

Examples

[ "10" -gt "2" ]  # Correct, numeric comparison
[ "10" > "2" ]    # Incorrect, this is string comparison (lexicographic)

File Test Path:

Examples

[ -f "$file" ]    # Correct, variable wrapped in quotes
[ -f $file ]      # Error occurs when the path contains spaces

Practical Application Examples

Example 1: Check if the Backup Directory Exists

Examples

backup_dir="/var/backups"
if [ ! -d "$backup_dir" ]; then
    mkdir -p "$backup_dir"
    echo "Creating backup directory:$backup_dir"
fi

Example 2: Validate User Input

Examples

read -p "Please enter age: " age
if [ "$age" -lt 0 -o "$age" -gt 120 ]; then
    echo "Invalid age input"
    exit 1
fi

Example 3: Service Startup Script

Examples

#!/bin/bash

if [ "$1" = "start" ]; then
    if [ -f "/var/run/service.pid" ]; then
        echo "Service is already running"
    else
        echo "Starting service..."
        # Start command
    fi
elif [ "$1" = "stop" ]; then
    # Stop logic
else
    echo "Usage: $0 {start|stop}"
fi

Summary

testThe command is a fundamental tool in shell script programming. Mastering it allows you to:

  • Implement conditional branching logic
  • Validate file and directory status
  • Compare strings and numeric values
  • Build complex evaluation conditions

Remember the key points:

  1. The bracket format is more commonly used, but pay attention to spaces
  2. Wrap variable references in double quotes
  3. Distinguish between string comparison and numeric comparison operators
  4. Use modern&&and||to replace-aand-o

Linux 命令大全Linux Command Encyclopedia

Other Extensions