25 advanced Bash scripting examples with code, output, and explanations. Learn advanced techniques for process control, text processing, networking, and more.
#!/bin/bash
# Monitor a process and restart if it dies
process_name="nginx"
max_restarts=3
restart_count=0
while [ $restart_count -lt $max_restarts ]; do
if ! pgrep -x "$process_name" > /dev/null; then
echo "Process $process_name is down. Attempting to restart ($((restart_count+1))/$max_restarts)..."
systemctl start $process_name
((restart_count++))
else
restart_count=0
fi
sleep 5
done
echo "Max restarts reached for $process_name. Alert needed!"
#!/bin/bash
# Parse and analyze Apache log file
log_file="/var/log/apache2/access.log"
echo "Top 10 IP addresses accessing the server:"
awk '{print $1}' "$log_file" | sort | uniq -c | sort -nr | head -10
echo -e "\nMost requested URLs:"
awk '{print $7}' "$log_file" | sort | uniq -c | sort -nr | head -10
echo -e "\nHTTP status codes count:"
awk '{print $9}' "$log_file" | sort | uniq -c | sort -nr
#!/bin/bash
# Process multiple files in parallel
echo "Processing image files in parallel..."
find . -name "*.jpg" -print0 | xargs -0 -P 4 -I {} bash -c '
file="{}"
echo "Processing $file"
convert "$file" -resize 800x600 "./processed/$(basename "$file")"
' _
echo "Parallel processing complete!"
#!/bin/bash
# Simple TCP server using bash
PORT=8080
LOG_FILE="socket_server.log"
echo "Starting TCP server on port $PORT..."
echo "Server started at $(date)" > "$LOG_FILE"
while true; do
# Listen for incoming connections
{
# Read the HTTP request header
while IFS= read -r line; do
[[ "$line" == $'\r' ]] && break
done
# Send HTTP response
echo -e "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello from Bash server! Time: $(date)"
} | nc -l $PORT -q 1
echo "Request received at $(date)" >> "$LOG_FILE"
done
#!/bin/bash
# System monitoring dashboard
display_stats() {
clear
echo "===== SYSTEM MONITORING DASHBOARD ====="
echo "Updated: $(date)"
echo "========================================"
echo -e "CPU Usage:\t$(top -bn1 | grep "Cpu(s)" | awk '{print $2}')%"
echo -e "Memory Usage:\t$(free -m | awk '/Mem:/ {printf "%.2f%%", $3/$2*100}')"
echo -e "Disk Usage:\t$(df -h / | awk '/\// {print $5}')"
echo -e "Running Processes: $(ps -e | wc -l)"
echo -e "Uptime: $(uptime -p)"
echo "========================================"
}
while true; do
display_stats
sleep 2
done
#!/bin/bash
# File encryption/decryption utility
encrypt_file() {
local file="$1"
local encrypted_file="$file.enc"
if [[ ! -f "$file" ]]; then
echo "Error: File $file not found!"
return 1
fi
echo "Encrypting $file..."
openssl enc -aes-256-cbc -salt -in "$file" -out "$encrypted_file"
if [[ $? -eq 0 ]]; then
echo "File encrypted successfully: $encrypted_file"
echo "Original file shredding..."
shred -u "$file"
else
echo "Encryption failed!"
fi
}
# Usage example
encrypt_file "sensitive_data.txt"