System Administration Scripts with Shell
In Linux and Unix systems, Shell scripts are the core tools for automating operations, batch data processing, and system configuration management. Compared to writing complex compiled language programs, Shell scripts have become system administrators' "second language" due to their lightweight nature, readability, and direct ability to invoke native operating system commands. Mastering Shell script writing means being able to automate a series of complex tasks—from file organization and log analysis to service start/stop—with minimal cost, thereby significantly enhancing system maintenance efficiency and stability.
A standard Shell script is typically read directly by an interpreter (such as /bin/bash) and executed line by line. Its core structure includes the Shebang line, variable definitions, command invocations, and conditional logic. The Shebang line is located on the first line of the file and is used to specify the interpreter that executes the script, for example #!/bin/bash.
When writing scripts, using variables appropriately is key to managing data. Shell supports two string formats: single quotes and double quotes, where variables within double quotes are automatically replaced. Additionally, $? can be used to retrieve the exit status of the previous command, which serves as the foundation for implementing error handling mechanisms.
#!/bin/bash
# Define variables
HOSTNAME="server-01"
LOG_DIR="/var/log/custom"
# Create directory (use -p argument to avoid errors on repeated execution)
mkdir -p "$LOG_DIR"
echo "Initializing system log service..."
Implementing Flow Control Mechanisms for Logical Control
To enable intelligent decision-making in scripts, conditional statements and loop structures must be introduced. The if-then-else structure allows the script to dynamically adjust its execution path based on system status, while for or while loops are suitable for batch processing repetitive tasks.
In conditional judgments, comparison operators such as -gt (greater than) and -eq (equal) are commonly used for numerical comparisons, while -d or -f are used to check if a file or directory exists. By combining && and || operators, complex logical chains can be constructed to ensure that critical tasks are triggered only under specific conditions.
# Check if disk space is sufficient
DISK_USAGE=$(df -h / | tail -1 | awk '{print $5}' | tr -d '%')
if [ "$DISK_USAGE" -gt 80 ]; then
echo "Warning: Disk usage exceeds 80%, cleanup script will be triggered soon."
# Execute cleanup logic
fi
Loop structures are particularly common in batch processing. for loops are suitable for iterations with a known quantity, while while loops are often used to wait for specific conditions to be met (such as port listening or process status checks). The shift parameter can conveniently pass and consume command-line arguments within the loop.
Enhancing Script Robustness: Error Handling and Logging
Scripts in production environments must possess strong fault tolerance capabilities. By setting the set -e option, the script will terminate immediately upon encountering any command with a non-zero exit status, preventing scenarios where partial tasks succeed while critical steps fail. Additionally, combining this with the trap mechanism allows for automatic cleanup operations after the script is unexpectedly interrupted (such as being forcefully killed), releasing temporary resources.
Logging is the primary source of information for diagnosing problems. One should not rely solely on echo output to the terminal; instead, logs should be written to files via redirection, distinguishing between informational, warning, and error-level messages. Using the date command to generate timestamps, combined with the logger tool to send logs to the system logging service, represents best practices for implementing standardized operations auditing.
#!/bin/bash
set -e
LOG_FILE="/var/log/script_execution.log"
# Define logging functions
log_info() { echo "[$(date '+%F %T')] [INFO] $*" | tee -a "$LOG_FILE"; }
log_error() { echo "[$(date '+%F %T')] [ERROR] $*" | tee -a "$LOG_FILE" >&2; }
# Set exit trap
cleanup() {
log_info "Script is executing cleanup operation..."
rm -rf /tmp/script_temp_*
}
trap cleanup EXIT
log_info "Starting system administration tasks..."
# ... Business logic ...
Practical Application: Automated Disk Space Inspection Script
To demonstrate the comprehensive application of the concepts above, we can construct an automated disk space inspection script. This script will iterate through all mount points in the system, calculate their usage rates, and generate a report and notify administrators when thresholds are exceeded. This script demonstrates the complete workflow of variables, conditional logic, loop iteration, and log integration.
#!/bin/bash
set -e
# Configuration parameters
THRESHOLD=80
REPORT_FILE="/root/disk_report_$(date '+%F_%H%M%S').txt"
log_info "Starting disk space inspection, threshold set to ${THRESHOLD}%"
# Iterate through all mount points
for MOUNT in /mnt/data /home /var /opt; do
if [ -d "$MOUNT" ]; then
USAGE=$(df -h "$MOUNT" | tail -1 | awk '{print $5}' | tr -d '%')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
log_error "Warning: Mount point ${MOUNT} usage is as high as ${USAGE}%, exceeding threshold!"
echo "$(date '+%F %T') Insufficient disk space: ${MOUNT} (${USAGE}%)" >> "$REPORT_FILE"
else
log_info "Status normal: ${MOUNT} (${USAGE}%)"
fi
fi
done
log_info "Inspection completed, report saved to ${REPORT_FILE}"
Through the study and practice of this guide, developers can gain a deep understanding of the powerful potential of Shell scripts in system administration. From basic syntax structures to complex error handling mechanisms, and finally to specific practical cases, Shell scripts are not only a sharp tool for automated operations but also an important carrier for cultivating systematic thinking. Mastering them will make the path of system management smoother and more efficient.