Linux Shell Script Explanation
Task 1: Disk Space Alert System
#!/bin/bash
threshold=80
usage=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
if [ $usage -gt $threshold ]; then
echo "Disk usage is above threshold. Current usage: $usage%"
fi
Explanation:
- #!/bin/bash: Shebang to use bash shell
- threshold=80: Variable for disk usage limit
- df /: Shows disk usage of root (/)
- grep /: Filters the line with the root mount
- awk '{ print $5 }': Prints the 5th column (usage %)
- sed 's/%//g': Removes the % symbol
- $(...): Command substitution to get output inside variable
- if [ $usage -gt $threshold ];: Condition check, -gt means greater than
- echo: Prints output to terminal
- fi: Ends the if block
Task 2: Old File Archiver
#!/bin/bash
target_dir="/path/to/target"
archive_dir="/path/to/archive"
mkdir -p "$archive_dir"
find "$target_dir" -type f -mtime +30 -exec mv {} "$archive_dir" \;
Explanation:
- mkdir -p: Create directory if it doesn't exist
- find: Search files
- -type f: Regular file type
- -mtime +30: Modified more than 30 days ago
- -exec mv {} "$archive_dir" \;: Move found files to archive_dir
- {}: Placeholder for each found file
- \;: Escapes semicolon which ends -exec command
Task 5: Zombie Process Detector
#!/bin/bash
ps -eo pid,ppid,state,cmd | awk '$3=="Z"{print $0}' >> /var/log/zombie_processes.log
Explanation:
- ps -eo: List all processes with specific fields
- awk '$3=="Z"{print $0}': Filters zombie (Z) processes
- >>: Appends output to file (vs > which overwrites)
Linux Shell Script Explanation
Task 7: Email Disk Usage Report
#!/bin/bash
df -h | mail -s "Daily Disk Usage Report" admin@example.com
Explanation:
- df -h: Human-readable disk usage
- mail -s: Send email with subject
Task 10: User Session Logger
#!/bin/bash
who >> /var/log/user_sessions.log
Explanation:
- who: Shows logged-in users
- >>: Appends to log file
Task 15: Kernel Version Checker
#!/bin/bash
current=$(uname -r)
latest=$(apt list --upgradable 2>/dev/null | grep linux-image | awk -F'/' '{print $2}' | head -1)
if [ "$current" != "$latest" ]; then
echo "Kernel is outdated: $current vs $latest" | mail -s "Kernel Update Alert" admin@example.com
fi
Explanation:
- uname -r: Current kernel version
- apt list --upgradable: Available updates
- grep linux-image: Finds kernel updates
- awk -F'/': Uses '/' as field separator
- head -1: Takes first result
- !=: Not equal condition
- mail -s: Send email
Task 41: Large File Finder with Age Filter
#!/bin/bash
find /path/to/search -type f -size +100M -mtime +15 -exec ls -lh {} \; > large_old_files_report.txt
Explanation:
- find: Search command
- -type f: Files only
- -size +100M: Files larger than 100MB
- -mtime +15: Modified more than 15 days ago
- -exec ls -lh {} \;: List details of each file
Linux Shell Script Explanation
- >: Redirect output (overwrite)