YouTip LogoYouTip

Linux Shell Test

The `test` command is a built-in conditional evaluation tool in Shell, used to evaluate expressions and return a boolean value (true/false). It is commonly used in conjunction with `if` statements and is fundamental for implementing logical control in Shell scripts. The `test` command in Shell is used to check whether a certain condition is met. It can perform tests in three aspects: numerical values, strings, and files. ### Syntax Format test EXPRESSION # or # Note that there must be spaces inside the square brackets * * * ## File Test Operations The `test` command is most commonly used to check file attributes. Here are the 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 | Is readable | `[ -r file.txt ]` | | -w | Is writable | `[ -w file.txt ]` | | -x | Is executable | `[ -x script.sh ]` | | -s | File size > 0 | `` | | -L | Is a symbolic link | `` | **Example Script**: ## Instance #!/bin/bash file="/etc/passwd" if[-e"$file"]; then echo"$file exists" if[-r"$file"]; then echo"and is readable" fi else echo"$file does not exist" fi The output result is: /etc/passwd exists and is readable * * * ## String Comparison `test` provides various ways to compare strings: | 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 Tip**: String variables should always be enclosed in double quotes to prevent syntax errors caused by empty variables. **Example**: ## Instance #!/bin/bash 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 tutorial in the terminal, and the output result is similar to the following: Enter username: tutorial Welcome, tutorial * * * ## Numerical Comparison For numerical comparison, `test` uses different operators: | 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**: ## Instance #!/bin/bash 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" fi After execution, we enter 12 in the terminal, and the output result is similar to the following: Enter age: 12Minor * * * ## Logical Operators `test` supports 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 `-a` and `-o`, which is more POSIX-compliant: ## Instance ["$a"-eq 1]&&["$b"-eq 2]# AND ["$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" =~ ^+$ ]]` * Safer string handling ### Arithmetic Comparison (( )) * Designed specifically for numerical comparison: `(( a > b ))` * Supports more complex arithmetic expressions **Example**: ## Instance if[["$file" == *.log ]]; then echo"This is a log file" fi if(($count>10)); then echo"Count exceeds 10" fi * * * ## Practical Application Examples ### 1. Check if a Service is Running ## Instance #!/bin/bash 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 fi ### 2. Backup File Check ## Instance #!/bin/bash backup_file="/backups/data_$(date +%Y%m%d).tar.gz" if[!-f"$backup_file"]; then echo"Error: backup file $backup_file does not exist" exit 1 elif[!-s"$backup_file"]; then echo"Warning: backup file is empty" else echo"Backup verification successful" fi * * * ## Common Errors and Debugging Tips 1. **Missing Spaces**: `[ "$a"="$b" ]` is incorrect; the correct form is `[ "$a" = "$b" ]` 2. **Unquoted Variables**: `[ -f $file ]` should be `[ -f "$file" ]` 3. **Confusing String and Numerical Comparison**: Use `=` for string comparison, `-eq` for numerical comparison Debugging Tip: Add `set -x` at the beginning of the script to enable debug mode, or use `echo` to print the test expression: ## Instance echo"Test expression: [ $a -eq $b ]" ["$a"-eq"$b"]&&echo"True"||echo"False"
← Python Tutorial - Getting StarDocker Compose Ls Command β†’