Skip to content

Instantly share code, notes, and snippets.

@marshki
Last active March 17, 2025 16:07
Show Gist options
  • Save marshki/c7822c9b1b1be19df0781b98dc203f90 to your computer and use it in GitHub Desktop.
Save marshki/c7822c9b1b1be19df0781b98dc203f90 to your computer and use it in GitHub Desktop.
Bash snippet to emit warning if capacity on disk(s) is ninety percent (90%) or more.
#!/usr/bin/env bash
#
# capacitOR
#
# Emit email to: "" if disk capacity is >= 90%
#
# Author: M. Krinitz <mjk235 [at] nyu [dot] edu>
# Date: 17-Mar-2025
# License: MIT
df="/usr/bin/df"
host="$(hostname -f)"
timestamp="$(date +"%b %d %X")"
recipients=""
log_file="/var/log/capacitOR.log"
# Set threshold, e.g. 90%
limit=${1:-90}
# Assumed `df` columns are:
# "Filesystem" "1024-blocks" "Used" "Available" "Capacity" "Mounted on"
# df (limit to local filesystem; POSIX output; block size 1k)
# grep to invert match
# Check exit code to make sure regex completed correctly
df_output="$($df --local --portability -k | grep -v '^Filesystem')"
if [ $? -ne 0 ]; then
printf "%s\n" "$(date +"%Y-%m-%d %H:%M:%S") - Error: df or grep failed." >&2
exit 1
fi
# If capacity less than limit, send out the Bat-signal
printf "%s" "$df_output" | while read -r Filesystem _ _ _ Capacity _ ; do
capacity="${Capacity%\%}"
if [[ "$capacity" -gt "$limit" ]]; then
message="On $host@$timestamp ${Filesystem} is ${Capacity} full. Please reduce disk capacity on impacted drive."
printf "%s\n" "$message" | mail -s "Disk capacity at $limit% on $host" "$recipients"
printf "%s\n" "$(date +"%Y-%m-%d %H:%M:%S") - Alert sent for $Filesystem on $host" >> "$log_file"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment