Final Challenges
Put your bash scripting skills to the test with these comprehensive challenges. Each challenge combines multiple concepts you've learned.
Challenge 1: File Statistics
Create a script that analyzes a directory and reports statistics:
#!/bin/bash
# Challenge: Implement file_stats function
file_stats() {
local dir="${1:-.}"
echo "=== Directory Statistics: $dir ==="
# TODO: Implement these
# 1. Count total files
# 2. Count total directories
# 3. Find largest file
# 4. Show file type distribution
}
Challenge 2: Text Processing Pipeline
Build a word frequency analyzer:
#!/bin/bash
# Analyze word frequency in a text file
analyze_words() {
local file="$1"
# Convert to lowercase, split words, count, sort
cat "$file" | \
tr '[:upper:]' '[:lower:]' | \
tr -cs '[:alpha:]' '\n' | \
sort | \
uniq -c | \
sort -rn | \
head -10
}
Challenge 3: Configuration Parser
Parse and validate a config file:
#!/bin/bash
# Parse key=value config file
declare -A CONFIG
parse_config() {
local file="$1"
while IFS='=' read -r key value; do
# Skip comments and empty lines
[[ "$key" =~ ^#.*$ || -z "$key" ]] && continue
# Trim whitespace
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
CONFIG["$key"]="$value"
done < "$file"
}
validate_config() {
local required=("host" "port" "user")
for key in "${required[@]}"; do
if [[ ! -v CONFIG[$key] ]]; then
echo "Missing required config: $key" >&2
return 1
fi
done
return 0
}
Challenge 4: Process Monitor
Monitor a process and restart if it dies:
#!/bin/bash
# Process watchdog
PROCESS_NAME="$1"
CHECK_INTERVAL=10
MAX_RESTARTS=3
RESTART_COUNT=0
start_process() {
echo "Starting $PROCESS_NAME..."
# Start your process here
"$PROCESS_NAME" &
}
check_process() {
pgrep -x "$PROCESS_NAME" > /dev/null
}
while true; do
if ! check_process; then
echo "Process $PROCESS_NAME not running!"
if [ $RESTART_COUNT -ge $MAX_RESTARTS ]; then
echo "Max restarts reached. Exiting."
exit 1
fi
start_process
RESTART_COUNT=$((RESTART_COUNT + 1))
fi
sleep $CHECK_INTERVAL
done
Challenge 5: Log Rotator
Implement log rotation:
#!/bin/bash
# Rotate log files
rotate_log() {
local log_file="$1"
local max_files="${2:-5}"
local max_size="${3:-10485760}" # 10MB
[ -f "$log_file" ] || return
# Check size
local size=$(stat -f%z "$log_file" 2>/dev/null || stat -c%s "$log_file")
[ "$size" -lt "$max_size" ] && return
echo "Rotating $log_file..."
# Rotate existing numbered logs
for ((i=max_files-1; i>=1; i--)); do
[ -f "${log_file}.$i" ] && mv "${log_file}.$i" "${log_file}.$((i+1))"
done
# Move current log
mv "$log_file" "${log_file}.1"
# Create new empty log
touch "$log_file"
# Remove oldest if over limit
[ -f "${log_file}.$((max_files+1))" ] && rm "${log_file}.$((max_files+1))"
}
Challenge 6: Directory Sync
Sync two directories with change detection:
#!/bin/bash
# Simple directory sync
sync_dirs() {
local src="$1"
local dst="$2"
# Find new or modified files
find "$src" -type f | while read -r file; do
rel_path="${file#$src/}"
dst_file="$dst/$rel_path"
# Check if needs sync
if [ ! -f "$dst_file" ] || [ "$file" -nt "$dst_file" ]; then
mkdir -p "$(dirname "$dst_file")"
cp "$file" "$dst_file"
echo "Synced: $rel_path"
fi
done
}
Challenge 7: Report Generator
Generate HTML reports from data:
#!/bin/bash
# Generate HTML report
generate_report() {
local title="$1"
local data_file="$2"
cat << EOF
<!DOCTYPE html>
<html>
<head><title>$title</title></head>
<body>
<h1>$title</h1>
<table border="1">
<tr><th>Name</th><th>Value</th></tr>
EOF
while IFS=',' read -r name value; do
echo "<tr><td>$name</td><td>$value</td></tr>"
done < "$data_file"
cat << EOF
</table>
<p>Generated: $(date)</p>
</body>
</html>
EOF
}
# Usage: generate_report "Status Report" data.csv > report.html
Challenge 8: Interactive Menu System
Create a full-featured menu:
#!/bin/bash
# Interactive menu system
show_menu() {
clear
echo "================================"
echo " System Administration"
echo "================================"
echo "1. Show disk usage"
echo "2. Show memory usage"
echo "3. Show running processes"
echo "4. Check network"
echo "5. Exit"
echo "================================"
}
while true; do
show_menu
read -p "Select option: " choice
case $choice in
1) df -h; read -p "Press Enter..." ;;
2) free -h; read -p "Press Enter..." ;;
3) ps aux | head -20; read -p "Press Enter..." ;;
4) ping -c 3 google.com; read -p "Press Enter..." ;;
5) echo "Goodbye!"; exit 0 ;;
*) echo "Invalid option"; sleep 1 ;;
esac
done
Final Project Ideas
- System Dashboard: Real-time system monitoring script
- Deployment Tool: Git-based deployment automation
- Backup Manager: Full backup solution with rotation
- Log Analyzer: Comprehensive log analysis tool
- Service Monitor: Multi-service health checker
Congratulations!
You've completed the Interactive Bash Scripting course! You've learned:
- Script fundamentals and execution
- Variables, quoting, and data types
- User input and argument handling
- Conditionals and control flow
- Loops and iteration
- Functions and scope
- String manipulation
- Arrays (indexed and associative)
- File processing
- Error handling and debugging
- Practical automation scripts
Continue practicing by automating tasks in your daily work. The best way to master bash is to use it regularly!
Key Takeaways
- Combine multiple concepts for powerful scripts
- Always handle errors gracefully
- Test scripts thoroughly before production use
- Comment your code for future reference
- Keep scripts modular and reusable
- Security matters - validate all input
- Performance matters - optimize when needed

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

