5月30日 00:10
How to use if statements and case statements for conditional judgment in Shell scripts?
Common conditional statements in Shell scripts include if statements, case statements, and test commands.
if Statement
Basic Syntax
bashif [ condition ]; then commands elif [ condition ]; then commands else commands fi
File Test Operators
bash[ -f file ] # File exists and is a regular file [ -d dir ] # Directory exists [ -e file ] # File or directory exists [ -r file ] # File is readable [ -w file ] # File is writable [ -x file ] # File is executable [ -s file ] # File size is greater than zero [ -L file ] # File is a symbolic link
String Test Operators
bash[ "$str1" = "$str2" ] # Strings are equal [ "$str1" != "$str2" ] # Strings are not equal [ -z "$str" ] # String is empty [ -n "$str" ] # String is not empty
Numeric Test Operators
bash[ $num1 -eq $num2 ] # Equal [ $num1 -ne $num2 ] # Not equal [ $num1 -gt $num2 ] # Greater than [ $num1 -lt $num2 ] # Less than [ $num1 -ge $num2 ] # Greater than or equal [ $num1 -le $num2 ] # Less than or equal
Logical Operators
bash[ condition1 ] && [ condition2 ] # Logical AND [ condition1 ] || [ condition2 ] # Logical OR ! [ condition ] # Logical NOT [ condition1 -a condition2 ] # Logical AND (inside []) [ condition1 -o condition2 ] # Logical OR (inside [])
if Statement Examples
bash#!/bin/bash # Check if file exists if [ -f "/etc/passwd" ]; then echo "File exists" else echo "File does not exist" fi # Check numeric value age=25 if [ $age -ge 18 ]; then echo "Adult" elif [ $age -ge 13 ]; then echo "Teenager" else echo "Child" fi # Compound condition if [ -f "$1" ] && [ -r "$1" ]; then echo "File exists and is readable" fi # Use [[ ]] for more complex tests if [[ $name == "John" || $name == "Jane" ]]; then echo "Welcome $name" fi
case Statement
Basic Syntax
bashcase $variable in pattern1) commands ;; pattern2) commands ;; *) commands ;; esac
case Statement Examples
bash#!/bin/bash # Simple menu selection echo "Select an option:" echo "1. Start" echo "2. Stop" echo "3. Restart" read -p "Enter choice: " choice case $choice in 1) echo "Starting service..." ;; 2) echo "Stopping service..." ;; 3) echo "Restarting service..." ;; *) echo "Invalid choice" ;; esac # Use pattern matching file="document.txt" case $file in *.txt) echo "Text file" ;; *.jpg|*.png) echo "Image file" ;; *) echo "Unknown file type" ;; esac
Test Commands
test Command
bashtest condition # Equivalent to [ condition ]
Double Brackets [[ ]]
bash# [[ ]] is a Bash extension with more powerful features [[ $name == "John" && $age -gt 18 ]]
Double Parentheses (( ))
bash# (( )) is used for arithmetic operations (( age++ )) if (( age >= 18 )); then echo "Adult" fi
Practical Application Example
bash#!/bin/bash # Check command line arguments if [ $# -eq 0 ]; then echo "Usage: $0 <filename>" exit 1 fi file=$1 # Check file type if [ -f "$file" ]; then echo "File exists" # Check file permissions if [ -r "$file" ]; then echo "File is readable" else echo "File is not readable" fi if [ -w "$file" ]; then echo "File is writable" else echo "File is not writable" fi elif [ -d "$file" ]; then echo "Directory exists" # Check directory contents file_count=$(ls -1 "$file" | wc -l) if [ $file_count -eq 0 ]; then echo "Directory is empty" else echo "Directory contains $file_count items" fi else echo "File or directory does not exist" exit 1 fi # Use case to handle file extensions extension="${file##*.}" case $extension in txt|md) echo "Text document" ;; sh) echo "Shell script" ;; py) echo "Python script" ;; *) echo "Unknown file type" ;; esac
Best Practices
- Always quote variables:
"$variable"prevents issues with spaces and special characters - Prefer [[ ]] over []: More powerful and safer
- Use case for multi-condition matching: Cleaner code
- Check command execution status: Use
$?orif command; then - Avoid using -a and -o: Use
&&and||for clarity