Advanced Linux Programming Examples

25 advanced Bash scripting examples with code, output, and explanations. Learn advanced techniques for process control, text processing, networking, and more.

📁 Example 1: Process Monitoring and Management
#!/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!"
Process nginx is down. Attempting to restart (1/3)... Process nginx is down. Attempting to restart (2/3)... Process nginx is down. Attempting to restart (3/3)... Max restarts reached for nginx. Alert needed!
Monitors a process and restarts it if it dies, with a maximum restart limit to prevent infinite loops.
process management pgrep systemctl
🔍 Example 2: Advanced Text Processing with AWK
#!/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
Top 10 IP addresses accessing the server: 142 192.168.1.23 128 192.168.1.45 98 192.168.1.102 76 192.168.1.87 54 192.168.1.63 43 192.168.1.29 32 192.168.1.156 21 192.168.1.201 18 192.168.1.5 12 192.168.1.99 Most requested URLs: 234 /index.html 187 /assets/style.css 156 /api/data 143 /images/logo.png 132 /about 121 /contact 98 /blog 87 /products 76 /privacy 54 /terms HTTP status codes count: 876 200 123 404 45 304 32 500 21 403
Uses AWK to parse and analyze Apache log files, extracting top IP addresses, requested URLs, and HTTP status code statistics.
awk text processing log analysis
🔄 Example 3: Parallel Processing with xargs
#!/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!"
Processing image files in parallel... Processing ./image1.jpg Processing ./image2.jpg Processing ./image3.jpg Processing ./image4.jpg Processing ./image5.jpg Parallel processing complete!
Uses xargs with parallel execution to process multiple files simultaneously, significantly improving performance for batch operations.
xargs parallel processing find
🌐 Example 4: Network Socket Programming
#!/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
Starting TCP server on port 8080... Request received at Wed Aug 25 15:42:33 UTC 2021 Request received at Wed Aug 25 15:43:12 UTC 2021 Request received at Wed Aug 25 15:43:47 UTC 2021
Implements a simple TCP server using netcat (nc) that responds to HTTP requests with a plain text message.
netcat socket programming TCP server
📊 Example 5: System Monitoring Dashboard
#!/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
===== SYSTEM MONITORING DASHBOARD ===== Updated: Wed Aug 25 15:45:22 UTC 2021 ======================================== CPU Usage: 15.2% Memory Usage: 45.78% Disk Usage: 67% Running Processes: 243 Uptime: up 2 days, 3 hours, 15 minutes ========================================
Creates a real-time system monitoring dashboard that displays CPU, memory, disk usage, and other system statistics.
system monitoring top free df
🔒 Example 6: File Encryption Script
#!/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"
Encrypting sensitive_data.txt... File encrypted successfully: sensitive_data.txt.enc Original file shredding...
Encrypts files using OpenSSL with AES-256-CBC encryption and securely deletes the original file using shred.
openssl encryption shred