Sub topic 11
Writing a Threshold Check for Space and Inodes
This chapter assumes that you can use a Linux shell, read df output, use sudo, and write basic Bash scripts. You will build a check that warns when either disk blocks or inodes reach a chosen percentage.
Decide what to measure
A filesystem has two independent limits:
- Space usage measures data blocks. A filesystem can have no free blocks even when it has unused inodes.
- Inode usage measures file records. A filesystem can have no free inodes even when it has free blocks.
A useful check examines both values for every real filesystem. It should ignore temporary filesystems because those often have short-lived or virtual storage.
| Value | Meaning | Warning example |
|---|---|---|
| `pcent` | Percentage of data blocks used | `/var` space at 85% |
| `ipcent` | Percentage of inodes used | `/var` inodes at 90% |
| `target` | Mount point being checked | `/`, `/var`, or `/home` |
df --output produces only the columns needed by the script. The -x options exclude filesystem types that you do not want to alert on.
Build the check
Save this as /usr/local/bin/check-disk.sh:
#!/usr/bin/env bash
# Usage: check-disk.sh [threshold_percent]
set -euo pipefail
threshold="${1:-85}"
if ! [[ "$threshold" =~ ^[0-9]+$ ]] || (( threshold > 100 )); then
echo "Usage: $0 [threshold 0-100]" >&2
exit 2
fi
df --output=pcent,ipcent,target \
-x tmpfs -x devtmpfs -x squashfs |
tail -n +2 |
while read -r use iuse mount; do
use="${use%\%}"
iuse="${iuse%\%}"
[[ "$use" =~ ^[0-9]+$ ]] || use=0
[[ "$iuse" =~ ^[0-9]+$ ]] || iuse=0
if (( use >= threshold )); then
echo "WARNING: $mount space at ${use}%"
fi
if (( iuse >= threshold )); then
echo "WARNING: $mount inodes at ${iuse}%"
fi
doneMake it executable and test it:
sudo install -m 0755 check-disk.sh /usr/local/bin/check-disk.sh
/usr/local/bin/check-disk.sh 85The first argument sets the threshold. If you omit it, the script uses 85 percent. A filesystem at exactly the threshold produces a warning because the comparison uses >=.
The pcent and ipcent fields normally contain values such as 42%. Removing the percent sign makes them usable in Bash arithmetic. The validation changes unexpected values, such as -, to zero instead of causing a script error.
Understand the check's output
The script prints nothing when every checked value is below the threshold. This makes it suitable for scheduled execution, because output indicates an exception.
If the script reports inode usage but space usage remains low, investigate directories containing many small files. If it reports space usage, inspect large directories and files. The same filesystem can trigger both warnings for different reasons.
Exercise
Exercise
What does the script report if /var uses 91% of its blocks and 40% of its inodes with a threshold of 85?
Show answer
It prints a space warning for /var at 91%. It does not print an inode warning because 40% is below 85%.