Sub topic 11
Writing a threshold check for space and inodes
This chapter assumes you can read df and df -i output and can write basic Bash with variables, pipes, and if statements. You will turn the manual checks from earlier chapters into a script that prints a warning when any real filesystem crosses a usage threshold, for either space or inodes.
What the check has to do
A manual df -h only tells you about the moment you run it. A threshold check applies the same reading to every filesystem and reports only the ones that need attention. It has to cover both limits:
- Space: the percentage of blocks in use.
- Inodes: the percentage of inodes in use. A filesystem full of tiny files can fail with "No space left on device" while
df -hshows plenty of free space.
It must also ignore filesystems that are noise: tmpfs, devtmpfs, and squashfs mounts (such as snap packages, which always show 100% used).
Getting machine-readable numbers from df
The default df output is meant for people. Parsing it with awk and column numbers breaks when a device name is long enough to wrap, or when the column order differs between versions. GNU df has --output, which selects the columns you want, in the order you want:
df --output=pcent,ipcent,target -x tmpfs -x devtmpfs -x squashfsTypical output:
Use% IUse% Mounted on
61% 8% /
12% 1% /boot
93% 72% /var/lib/dataThree points matter here:
pcentis the percentage of blocks used.ipcentis the percentage of inodes used.targetis the mount point.- The first line is a header, so the script removes it with
tail -n +2. -xexcludes a filesystem type. You can repeat it. Add-x overlayif the host runs containers and you do not want container layers reported.
Filesystems that do not use a fixed inode table, such as Btrfs, report - instead of a percentage for inodes. If you compare - as a number, Bash raises an error. The script therefore replaces anything non-numeric with 0.
The script
Save this as /usr/local/bin/check-disk.sh and make it executable with sudo chmod 755 /usr/local/bin/check-disk.sh.
#!/usr/bin/env bash
# Usage: check-disk.sh [threshold_percent]
set -euo pipefail
threshold="${1:-85}"
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
doneHow it works
set -euo pipefailstops the script on errors, on unset variables, and when any command in a pipeline fails. Withoutpipefail, a failingdfwould be hidden by the successful commands after it.threshold="${1:-85}"uses the first argument as the threshold, or 85 if none is given.read -r use iuse mountsplits each line into three fields. The last variable receives the rest of the line, so a mount point with spaces in its name is still read whole.${use%\%}removes a trailing%character from the value, leaving a bare number.[[ "$use" =~ ^[0-9]+$ ]] || use=0checks that the value is made only of digits. If not, it is set to 0.(( use >= threshold ))is an arithmetic comparison. It runs insideif, so a false result does not triggerset -e.
Run it with a low threshold to confirm it works before you trust it:
/usr/local/bin/check-disk.sh 1Every real filesystem should produce at least one warning. Then run it with the default and expect no output on a healthy server. Silence is the normal result.
Choosing a threshold
A single number is easy to configure, but it does not suit every filesystem equally.
| Situation | Reasoning |
|---|---|
| 80 to 85% on a small root filesystem | Little headroom. Logs or a package upgrade can use the remaining space in minutes. |
| 85 to 90% on a large data volume | 10% of a multi-terabyte disk is still a lot of room, so a slightly higher number is acceptable. |
| 90% or more | Treat as urgent. Some filesystems slow down when nearly full, and recovery gets harder. |
| Inodes at any high percentage | Inode use usually grows in steps, such as a runaway session directory, so a warning at 85% leaves little time. Consider a lower inode threshold. |
The Use% that df reports is computed against space available to ordinary users. On ext4, blocks reserved for root (5% by default) are not counted as available, so a filesystem can show 100% while root can still write. Do not read an 85% threshold as "15% of the raw disk is free". A later chapter covers reserved blocks and how ext4, XFS, and Btrfs differ.
Separate thresholds for space and inodes
The script above applies one threshold to both. If you want different values, take two arguments:
#!/usr/bin/env bash
# Usage: check-disk.sh [space_threshold] [inode_threshold]
set -euo pipefail
space_limit="${1:-85}"
inode_limit="${2:-80}"
for value in "$space_limit" "$inode_limit"; do
[[ "$value" =~ ^[0-9]+$ ]] || { echo "Thresholds must be whole numbers" >&2; exit 2; }
done
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 >= space_limit )); then
echo "WARNING: $mount space at ${use}%"
fi
if (( iuse >= inode_limit )); then
echo "WARNING: $mount inodes at ${iuse}%"
fi
doneThe extra loop rejects an argument such as 85% or abc early. Otherwise the arithmetic would fail partway through the output with a confusing error.
Returning an exit status
The script prints warnings but always exits with status 0 when it finds problems. That is fine when you read the output, but monitoring tools and cron wrappers often decide on the exit code. The reason a simple counter does not work is that the while loop at the end of a pipeline runs in a subshell. A variable set inside it is lost when the loop ends. Reading from process substitution keeps the loop in the main shell:
#!/usr/bin/env bash
# Usage: check-disk.sh [threshold_percent]
# Exit status: 0 = all clear, 1 = at least one warning
set -euo pipefail
threshold="${1:-85}"
status=0
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}%"
status=1
fi
if (( iuse >= threshold )); then
echo "WARNING: $mount inodes at ${iuse}%"
status=1
fi
done < <(df --output=pcent,ipcent,target -x tmpfs -x devtmpfs -x squashfs | tail -n +2)
exit "$status"One trade-off: with process substitution, set -o pipefail does not catch a failure of df inside < <(...). If df fails, the loop sees no input and the script reports success. The pipeline version in the first script does not have this weakness, so choose based on whether you need the exit code or the failure detection. A common compromise is to use the pipeline version and let the scheduler capture its output.
Common errors
df: unrecognized option '--output'. Thisdfis not the GNU version. BusyBox and older systems lack the option. Check withdf --version.syntax error: operand expected. A value was not a number, usually a-for inodes on Btrfs. The=~ ^[0-9]+$guard prevents this. If you removed it, restore it.- Warnings for snap or container mounts. Add
-x squashfsor-x overlay. Snap images are read-only and always full, so they will never improve. - A mount point that is not listed.
dfshows only mounted filesystems. If a volume failed to mount, its files are being written to the directory on the parent filesystem, and the check may report the parent as filling up. Compare withfindmntwhen a warning looks wrong. - The script works in your shell but not elsewhere. Schedulers run with a minimal
PATH. Use the absolute path to the script. The next chapter covers scheduling in detail.
Exercise
A server's Btrfs data volume has a - in the IUse% column of df. The script from this chapter, with the non-numeric guard removed, stops with "operand expected". Explain why this happens, and say what the fixed script does with that value.
Show answer
Btrfs allocates metadata dynamically and has no fixed inode count, so df reports - for inode percentage. Bash's (( iuse >= threshold )) expects a number, and - is not one, so the arithmetic fails. The guard [[ "$iuse" =~ ^[0-9]+$ ]] || iuse=0 replaces the value with 0, so the inode comparison is skipped for that mount while the space check still runs normally.
Exercise
You want the script to report a failure status to a monitoring tool when any filesystem is over the threshold. Why does adding status=1 inside the while loop of the pipeline version not work, and what change fixes it?
Show answer
In df ... | tail ... | while ..., the loop runs in a subshell, so any variable it sets is discarded when the loop ends and the final exit sees the original value, 0. Feeding the loop with process substitution, done < <(df ... | tail -n +2), keeps the loop in the main shell, so status=1 survives and exit "$status" returns 1 when a warning was printed.