Learn to write and understand practical Bash scripts for common automation tasks.
Develop scripts that interact with files, directories, logs, and system information.
Apply error handling, input validation, and logging to these scripts.
Chapter Outline:
1. Disk Usage Report
Script Overview:
This script generates a detailed disk usage report for the user, highlighting space usage by directories.
#!/bin/bash# Check if directory path is providedif[-z"$1"];thenecho"Usage: $0 <directory_path>"exit1fidirectory="$1"# Check if the directory existsif[!-d"$directory"];thenecho"Directory not found: $directory"exit1fi# Display disk usage reportdu-sh"$directory"/*|sort-rh>disk_usage_report.txtecho"Disk usage report saved to disk_usage_report.txt"
netstat -tunapl shows active network connections along with their listening ports (t for TCP, u for UDP, n for numeric IPs, a for all connections, p for programs).
Logging:
The output of netstat is appended to network_connections.log, which includes a timestamp ($(date)).
Real-World Use:
This is useful for monitoring network activity, detecting potential intrusions, or identifying suspicious connections.
3. Automated Backup of Log Files
Script Overview:
A script to automate the backup of system log files.
#!/bin/bash
# Define source and backup directories
log_dir="/var/log"
backup_dir="/backup/logs"
timestamp=$(date +"%Y%m%d_%H%M%S")
# Check if backup directory exists, if not create it
if [ ! -d "$backup_dir" ]; then
mkdir -p "$backup_dir"
fi
# Archive and compress log files
tar -czf "$backup_dir/log_backup_$timestamp.tar.gz" -C "$log_dir" .
echo "Log backup completed: log_backup_$timestamp.tar.gz"
#!/bin/bash
# Display top 5 CPU-consuming processes
echo "Top 5 CPU-consuming processes:"
ps -eo pid,comm,%cpu --sort=-%cpu | head -n 6
# Ask user if they want to kill any process
read -p "Enter the PID of the process to kill (or press Enter to skip): " pid
# If the user provided a PID, kill the process
if [ -n "$pid" ]; then
kill -9 "$pid"
echo "Process $pid killed."
else
echo "No process killed."
fi