Practical Linux Scripting
Real-World Test Command Applications
System Health Monitoring Script
#!/bin/bash
## System Health Check Script
check_system_health() {
## Check disk space
if [ $(df -h / | awk '/\// {print $(NF-1)}' | sed 's/%//') -gt 90 ]; then
echo "WARNING: Disk space is critically low!"
fi
## Check memory usage
if [ $(free | grep Mem | awk '{print $3/$2 * 100.0}') -gt 80 ]; then
echo "WARNING: High memory consumption detected!"
fi
## Check for zombie processes
if [ $(ps aux | grep defunct | wc -l) -gt 0 ]; then
echo "WARNING: Zombie processes found!"
fi
}
Automated Backup Script
#!/bin/bash
## Backup Script with Conditional Checks
perform_backup() {
BACKUP_DIR="/home/user/backups"
SOURCE_DIR="/home/user/documents"
## Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
echo "Source directory does not exist!"
exit 1
}
## Check if backup directory is writable
if [ ! -w "$BACKUP_DIR" ]; then
echo "Backup directory is not writable!"
exit 1
}
## Perform backup
tar -czf "$BACKUP_DIR/backup_$(date +%Y%m%d).tar.gz" "$SOURCE_DIR"
}
User Management Script
#!/bin/bash
## Advanced User Management
create_user() {
USERNAME=$1
PASSWORD=$2
## Validate input
if [ -z "$USERNAME" ] || [ -z "$PASSWORD" ]; then
echo "Username and password are required!"
exit 1
}
## Check if user already exists
if id "$USERNAME" &>/dev/null; then
echo "User already exists!"
exit 1
}
## Create user with password
useradd -m "$USERNAME"
echo "$USERNAME:$PASSWORD" | chpasswd
}
Script Workflow Patterns
graph TD
A[Script Workflow] --> B[Input Validation]
A --> C[Conditional Checks]
A --> D[Error Handling]
B --> B1[Validate Arguments]
B --> B2[Check Input Types]
C --> C1[System Conditions]
C --> C2[Resource Availability]
D --> D1[Exit Codes]
D --> D2[Error Logging]
Best Practices for Test Command Usage
Practice |
Description |
Example |
Quote Variables |
Prevent word splitting |
[ "$var" = "value" ] |
Use Double Brackets |
Enhanced testing in Bash |
[[ $var =~ pattern ]] |
Handle Edge Cases |
Check for null/empty values |
[ -n "$variable" ] |
Advanced Conditional Techniques
#!/bin/bash
## Complex Condition Handling
process_file() {
local file=$1
## Multiple condition checks
if [[ -f "$file" ]] && [[ -r "$file" ]] && [[ -s "$file" ]]; then
echo "File is valid for processing"
## Process file logic here
else
echo "File does not meet processing requirements"
fi
}
Error Handling and Logging
#!/bin/bash
## Comprehensive Error Handling
log_error() {
local message=$1
echo "[ERROR] $(date): $message" >> /var/log/script_errors.log
exit 1
}
## Example usage
[ -d "/path/to/directory" ] || log_error "Directory does not exist"
LabEx Recommendation
LabEx suggests practicing these scripts in controlled environments to build practical Linux scripting skills and understand test command nuances.