mirror of
https://github.com/AlexMacocian/ServerManagementUtils.git
synced 2026-07-15 15:19:58 +00:00
62 lines
2.3 KiB
Bash
62 lines
2.3 KiB
Bash
#!/bin/bash
|
|
|
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
. "${SCRIPT_DIR}/../share/logging.sh"
|
|
. "${SCRIPT_DIR}/../share/os-detection.sh"
|
|
|
|
LOGFILE=/var/log/disk_usage.log
|
|
OS_TYPE=$(DetectOS)
|
|
|
|
# Create log file with proper error handling
|
|
if ! touch "$LOGFILE" 2>/dev/null; then
|
|
LogError "Cannot create log file $LOGFILE"
|
|
exit 1
|
|
fi
|
|
chmod 644 "$LOGFILE" 2>/dev/null
|
|
|
|
LogInformation "Starting disk usage monitoring (OS: $OS_TYPE)"
|
|
|
|
for i in {1..6}; do
|
|
timestamp=$(GetTimestamp)
|
|
|
|
# Use process substitution instead of pipe to avoid subshell issues
|
|
if [[ "$OS_TYPE" == "macos" ]]; then
|
|
# macOS df format: Filesystem 512-blocks Used Available Capacity iused ifree %iused Mounted on
|
|
# Mount points can have spaces, so we need to handle the full line
|
|
while IFS= read -r line; do
|
|
# Skip header line
|
|
if [[ "$line" =~ ^Filesystem ]]; then
|
|
continue
|
|
fi
|
|
|
|
# Extract fields using awk (handles multi-word mount points)
|
|
filesystem=$(echo "$line" | awk '{print $1}')
|
|
blocks=$(echo "$line" | awk '{print $2}')
|
|
used=$(echo "$line" | awk '{print $3}')
|
|
# Mount point is everything from column 9 onwards
|
|
mount=$(echo "$line" | awk '{for(i=9;i<=NF;i++) printf "%s%s", $i, (i<NF?" ":""); print ""}')
|
|
|
|
# Skip entries with 0 blocks (pseudo filesystems) or filesystem starting with dash
|
|
if [[ -n "$mount" && -n "$used" && -n "$blocks" && "$blocks" != "0" && "$filesystem" != "-" ]]; then
|
|
used_bytes=$((used * 512))
|
|
total_bytes=$((blocks * 512))
|
|
echo "$timestamp $mount $used_bytes $total_bytes" >> "$LOGFILE"
|
|
fi
|
|
done < <(df 2>/dev/null)
|
|
else
|
|
# Linux df with --output flag
|
|
while read -r mount used total; do
|
|
if [[ -n "$mount" && -n "$used" && -n "$total" ]]; then
|
|
echo "$timestamp $mount $used $total" >> "$LOGFILE"
|
|
fi
|
|
done < <(df --output=target,used,size -B1 2>/dev/null | tail -n +2)
|
|
fi
|
|
|
|
LogInformation "Disk usage data collected (iteration $i/6)"
|
|
|
|
if [ $i -lt 6 ]; then
|
|
sleep 10
|
|
fi
|
|
done
|
|
|
|
LogInformation "Disk usage monitoring completed" |