Linux Command Line Scripting Teaching Plan

Lesson 1: File Handling and Automation

1.1. Create and Archive Backup

#!/bin/bash
tar -czf /backups/$(date +%Y%m%d).tar.gz /source/directory
echo "Backup created: $(date)"
        

Automates daily backups with timestamped filenames.

1.2. Delete Old Logs

#!/bin/bash
find /var/log/ -type f -name "*.log" -mtime +7 -exec rm -f {} \;
echo "Old logs removed"
        

Removes logs older than 7 days using find.

1.3. Search and Replace in Files

#!/bin/bash
find . -type f -name "*.txt" -exec sed -i 's/old_string/new_string/g' {} \;
echo "Files updated"
        

Recursively replaces text in all .txt files.

1.4. Directory Size Report

#!/bin/bash
du -h --max-depth=1 /path/to/directory | sort -hr > size_report.txt
        

Generates a human-readable directory size report.

1.5. Create Multiple Users

#!/bin/bash
for user in user1 user2 user3
do
    useradd -m $user && echo "User $user created"
done
        

Batch creates users with home directories.

Lesson 2: Text Processing and Parsing

2.1. Parse Apache Logs

#!/bin/bash
awk '{print $1, $9}' /var/log/apache2/access.log | grep "200" > successful_requests.txt
        

Extracts successful (200) requests from Apache logs.

2.2. Count Word Frequencies

#!/bin/bash
grep -oEw '\w+' file.txt | sort | uniq -c | sort -nr > word_count.txt
        

Generates a sorted word frequency report.

2.3. CSV Column Extraction

#!/bin/bash
awk -F',' '{print $1, $3}' data.csv > extracted_columns.csv
        

Extracts specific columns from a CSV file.

2.4. IP Address Validation

#!/bin/bash
echo "Enter IP:"
read ip
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Valid IP"
else
    echo "Invalid format"
fi
        

Validates user input for IP addresses.

2.5. JSON Parsing

#!/bin/bash
curl -s http://api.example.com/data | jq '.items[].name'
        

Uses jq to extract JSON data from an API.

Lesson 3: Process and System Control

3.1. Monitor Process Memory

#!/bin/bash
while true
do
    ps -eo pid,ppid,cmd,%mem --sort=-%mem | head -n 11
    sleep 2
done
        

Continuous top 10 memory-consuming processes monitoring.

3.2. Auto-Restart Service

#!/bin/bash
while true
do
    systemctl status nginx &> /dev/null || systemctl start nginx
    sleep 60
done
        

Keeps Nginx running by restarting on failure.

3.3. Execute with Elevated Privileges

#!/bin/bash
sudo apt update && sudo apt upgrade -y
        

Updates all packages with root privileges.

3.4. Log Rotation Script

#!/bin/bash
find /var/log/ -name "*.log" -mtime +30 -exec gzip {} \;
        

Compresses logs older than 30 days.

3.5. System Information Report

#!/bin/bash
echo "CPU Info:"
lscpu
echo "Memory Usage:"
free -h
echo "Disk Usage:"
df -h
        

Generates a system hardware report.

Lesson 4: Networking and Remote Access

4.1. SSH Tunnel Setup

#!/bin/bash
ssh -L 8080:localhost:80 user@192.168.1.100
        

Creates a local port forwarding tunnel.

4.2. Ping Sweep

#!/bin/bash
for ip in {1..254}
do
    ping -c 1 192.168.1.$ip &> /dev/null && echo "Host 192.168.1.$ip is up"
done
        

Scans local network for active hosts.

4.3. Download and Verify

#!/bin/bash
wget http://example.com/file.iso && sha256sum file.iso | grep -q "expected_hash"
        

Downloads a file and checks its integrity.

4.4. Port Scanning

#!/bin/bash
nmap -p 1-1000 -sT 192.168.1.50
        

Scans open ports on a target IP.

4.5. Automated SFTP Transfer

#!/bin/bash
lftp -u user,password sftp://server.com -e "mirror /remote/directory /local/directory; quit"
        

Automates secure file transfers with lftp.

Lesson 5: Advanced Scripting Techniques

5.1. Functions and Parameters

#!/bin/bash
greet() {
    echo "Hello, $1!"
}
greet $USER
        

Defines and uses a parameterized function.

5.2. Error Handling with Traps

#!/bin/bash
trap 'echo "Aborted by user"; exit 1' SIGINT
echo "Running..."
sleep 100
        

Captures Ctrl+C and handles gracefully.

5.3. Case Statement Menu

#!/bin/bash
echo "Choose [1] Backup, [2] Restore"
read choice
case $choice in
    1) echo "Backup selected";;
    2) echo "Restore selected";;
    *) echo "Invalid option";;
esac
        

Implements a menu-driven interface.

5.4. Parallel Processing

#!/bin/bash
parallel -j 4 echo {} ::: arg1 arg2 arg3 arg4
        

Runs commands in parallel across threads.

5.5. Here Document for Configuration

#!/bin/bash
cat <<EOF > /etc/nginx/sites-available/new.conf
server {
    listen 80;
    server_name example.com;
    location / {
        root /var/www/html;
    }
}
EOF
        

Creates configuration files dynamically.

Lesson 6: System Automation and Monitoring

6.1. Cron Job for Daily Backup

0 2 * * * /usr/local/bin/backup.sh
        

Schedules a backup script to run daily at 2 AM.

6.2. Disk Space Alert

#!/bin/bash
if [ $(df / | awk '{print $5}' | tail -1 | sed 's/%//') -ge 90 ]; then
    echo "Disk space critical!" | mail -s "Alert" admin@example.com
fi
        

Sends an email alert when disk usage exceeds 90%.

6.3. User Management Script

#!/bin/bash
useradd -m -s /bin/bash $1 && echo "$1 created"
        

Creates a new user when passed as an argument.

6.4. Firewall Configuration

#!/bin/bash
ufw allow ssh
ufw allow http
ufw enable
        

Automates firewall setup.

6.5. System Performance Dashboard

#!/bin/bash
watch -n 5 'ps -eo %cpu,%mem,comm --sort=-%cpu | head -n 10'
        

Creates a real-time system performance monitor.

Conclusion

This plan covers essential scripting techniques using intermediate to advanced Linux commands. Each example builds foundational skills while demonstrating practical automation scenarios. To master these concepts:

Pro Tip: Use set -x in scripts to enable debug mode for troubleshooting.