Interview Question: Disk Space Monitoring Approach
Approach to creating a bash script that checks storage and alerts when it exceeds 70%
Interview Question: Disk Space Monitoring Approach
The Question
“Write a bash shell script which will check the storage and if it is more than 70% will alert. It doesn’t have to be working or perfect; I want to know how you approach it or how the template should look like.”
My Approach
When approaching this problem, I would:
- First identify the key requirements:
- Need to check disk storage usage
- Compare against a 70% threshold
- Generate an alert if threshold is exceeded
- Determine the bash commands needed:
dfcommand to get disk usage information- Parsing tools like
grep,awkto extract percentages - Conditional logic to compare against threshold
- Create a script structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# Script to check disk usage and alert if over threshold
# Set threshold percentage
THRESHOLD=70
# Get disk usage percentage for root filesystem (/)
USAGE=$(df -h / | grep -v Filesystem | awk '{print $5}' | tr -d '%')
# Check if usage exceeds threshold
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "ALERT: Disk usage is at $USAGE%, which exceeds threshold of $THRESHOLD%"
# Here you could add additional alert methods:
# - Send email
# - Log to a file
# - Trigger system notification
# - Call webhook for monitoring system
else
echo "Disk usage is at $USAGE%, below threshold of $THRESHOLD%"
fi
This script:
1
2
3
4
5
6
1. Sets a threshold value (70%)
2. Uses df command to get disk usage information
3. Extracts just the percentage using grep and awk
4. Removes the % sign
5. Compares the usage against the threshold
6. Outputs an alert message if threshold is exceeded
- Mention potential improvements:
- The script could be enhanced to check multiple filesystems
- Could add flexibility with command-line arguments
- Could implement different notification methods
- Add logging capabilities
- Set up as a cron job for regular monitoring
This post is licensed under CC BY 4.0 by the author.