7.5. Lab: Automation Scripts#
Apply control flow to build practical, real-world automation scripts.
7.5.1. Exercise 6: System Monitor#
Create a script sysmonitor.sh that:
Shows current date/time
Shows disk usage for
/Shows top 3 memory-hungry processes
Shows network interfaces and IP addresses
Runs continuously (optional: add refresh interval)
Example:
$ bash sysmonitor.sh
=== System Monitor ===
Date: Thu Jan 1 12:00:00 UTC 2024
Disk Usage: 45%
Top Memory Users:
1. systemd (256MB)
2. bash (128MB)
3. sshd (64MB)
Network: 192.168.1.100 (eth0)
Hints:
Use
datefor timeUse
dffor disk usageUse
psfor processesUse
ip addrfor network infoOptional: use
while truewithsleepfor refresh
7.5.2. Exercise 5: Log Analyzer#
Create a script analyze_logs.sh that:
Takes a log file as argument
Counts error, warning, and info lines
Shows lines containing “ERROR”
Skips comment lines (starting with #)
Shows summary statistics
Example:
$ bash analyze_logs.sh app.log
=== Log Analysis ===
Total lines: 100
Errors: 5
Warnings: 12
Info: 83
Error lines:
[Error 1]
[Error 2]
...
Hints:
Use
while readto read file line by lineUse
continueto skip comments and empty linesUse
grepor[[ ]]to check for keywordsCount occurrences in variables
7.5.3. Exercise 4: Backup Script#
Create a script backup.sh that:
Takes a source directory and destination
Validates both paths exist
Creates backup with timestamp
Shows progress while copying files
Reports final status
Example:
$ bash backup.sh /home/user/docs /backup
Validating paths...
Source: /home/user/docs ✓
Target: /backup ✓
Backing up: file1.txt
Backing up: file2.txt
Backed up 2 files
Backup complete: /backup/docs.backup.20240101_120000
Hints:
Use arguments
$1and$2Use
-dto check if directory existsUse timestamp:
date +%Y%m%d_%H%M%SUse
forloop to process filesEcho progress messages
7.5.4. Exercise 3: User Input Validator#
Create a script register.sh that:
Asks for username (3+ characters)
Asks for email (must contain @)
Asks for age (must be number >= 18)
Validates each input
Shows success or error messages
Example:
$ bash register.sh
Enter username (3+ chars): ab
Invalid: too short
Enter username (3+ chars): alice
Enter email: alice@example.com
Enter age: 20
Registration successful!
Hints:
Use
read -pfor promptsUse
[[ ]]for string/pattern matchingUse
=~for regex patternsLoop if validation fails
7.5.5. Exercise 2: File Processor#
Create a script process_files.sh that:
Takes a directory as argument
Processes each
.txtfile in that directoryShows filename and line count
Counts total lines across all files
Example:
$ bash process_files.sh /tmp
Processing file1.txt: 42 lines
Processing file2.txt: 18 lines
Total across 2 files: 60 lines
Hints:
Use
forloop with glob patternUse
wc -lto count linesUse variable to accumulate totals
Check if directory exists first