Shell test Command
testThe command is a Shell built-in conditional judgment tool used to evaluate expressions and return a boolean value (true/false). It is usually used withifstatements, and is the foundation for implementing logical control in Shell scripts.
The test command in Shell is used to check whether a condition holds true. It can perform tests in three areas: numeric values, strings, and files.
Syntax Format
test EXPRESSION # 或 [ EXPRESSION ] # 注意方括号内必须有空格
File Test Operations
testThe command is most commonly used to check file attributes. Below are common file test options:
| Operator | Description | Example |
|---|---|---|
| -e | File exists | [ -e file.txt ] |
| -f | Is a regular file | [ -f /path/to/file ] |
| -d | Is a directory | [ -d /path/to/dir ] |
| -r | Readable | [ -r file.txt ] |
| -w | Writable | [ -w file.txt ] |
| -x | Executable | [ -x script.sh ] |
| -s | File size > 0 | [ -s logfile ] |
| -L | Is a symbolic link | [ -L symlink ] |
Example Script:
Examples
file="/etc/passwd"
if [ -e "$file" ]; then
echo "$fileexists"
if [ -r "$file" ]; then
echo "and is readable"
fi
else
echo "$filedoes not exist"
fi
The output result is:
/etc/passwd 存在 并且可读
String Comparison
testProvides multiple string comparison methods:
| Operator | Description | Example |
|---|---|---|
| -z STRING | String is empty | [ -z "$var" ] |
| -n STRING | String is not empty | [ -n "$var" ] |
| STRING1 = STRING2 | Strings are equal | [ "$var1" = "$var2" ] |
| STRING1 != STRING2 | Strings are not equal | [ "$var1" != "$var2" ] |
Important Note: String variables should always be enclosed in double quotes to prevent empty variables from causing syntax errors.
Example:
Examples
read -p "Enter username: " username
if [ -z "$username" ]; then
echo "Error: username cannot be empty"
exit 1
elif [ "$username" = "root" ]; then
echo "Warning: using the root account is not recommended"
else
echo "Welcome,$username"
fi
After execution, we enter example in the terminal, and the output is similar to the following:
输入用户名: example 欢迎, example
Numeric Comparison
For numeric comparison,testdifferent operators are used:
| Operator | Description | Example |
|---|---|---|
| -eq | Equal to | [ "$a" -eq "$b" ] |
| -ne | Not equal to | [ "$a" -ne "$b" ] |
| -gt | Greater than | [ "$a" -gt "$b" ] |
| -ge | Greater than or equal to | [ "$a" -ge "$b" ] |
| -lt | Less than | [ "$a" -lt "$b" ] |
| -le | Less than or equal to | [ "$a" -le "$b" ] |
Example:
Examples
read -p "Enter age: " age
if [ "$age" -lt 0 ]; then
echo "Age cannot be negative"
elif [ "$age" -lt 18 ]; then
echo "Minor"
elif [ "$age" -ge 18 ] && [ "$age" -lt 60 ]; then
echo "Adult"
else
echo "Senior citizen"
fi
After execution, we enter 12 in the terminal, and the output is similar to the following:
输入年龄: 12 未成年人
Logical Operators
testSupports logical combinations:
| Operator | Description | Example |
|---|---|---|
| ! | Logical NOT | [ ! -f "$file" ] |
| -a | Logical AND | [ "$a" -eq 1 -a "$b" -eq 2 ] |
| -o | Logical OR | [ "$a" -eq 1 -o "$b" -eq 2 ] |
Modern recommended syntax: Use&&and||instead of-aand-o, which is more POSIX-compliant:
Examples
[ "$a" -eq 1 ] || [ "$b" -eq 2 ] # OR
Advanced Usage: [[ ]] and (( ))
Bash provides more powerful test syntax:
Double Brackets [[ ]]
- Supports pattern matching:
[[ "$var" == *.txt ]] - Supports regular expressions:
[[ "$var" =~ ^[0-9]+$ ]] - Safer string handling
Arithmetic Comparison (( ))
- Designed specifically for numeric comparison:
(( a > b )) - Supports more complex arithmetic expressions
Example:
Examples
echo "This is a log file"
fi
if (( $count > 10 )); then
echo "The count exceeds 10"
fi
Practical Application Examples
1. Check if a service is running
Examples
service="nginx"
if systemctl is-active --quiet "$service"; then
echo "$service"is running"
else
echo "$service"is not running"
# You can add a command to start the service here
fi
2. Backup File Check
Examples
backup_file="/backups/data_$(date +%Y%m%d).tar.gz"
if [ ! -f "$backup_file" ]; then
echo "Error: backup file$backup_filedoes not exist"
exit 1
elif [ ! -s "$backup_file" ]; then
echo "Warning: backup file is empty"
else
echo "Backup verification succeeded"
fi
Common Errors and Debugging Tips
- Missing space:
[ "$a"="$b" ]is wrong, the correct form is[ "$a" = "$b" ] - Unquoted variable:
[ -f $file ]should be[ -f "$file" ] - Confusing string and numeric comparison: Use
=for comparing strings,-eqfor comparing numeric values
Debugging tip: Add at the beginning of the scriptset -xto enable debug mode, or useechoto print the test expression:
Examples
[ "$a" -eq "$b" ] && echo "is true" || echo "is false"