Sub topic 3
Watching Disk Space and Inode Usage on a Linux Server
This chapter assumes you can use sudo, read df and du output, and write simple Bash scripts with variables, pipes, and if statements.
Taming logs with logrotate and journald limits
Logs are the most common cause of steady disk growth. logrotate is a tool that renames, compresses, and deletes old log files on a schedule. Add a file in /etc/logrotate.d/ for each application:
/var/log/myapp/*.log {
weekly
rotate 4
compress
missingok
notifempty
}The systemd journal is a separate log store managed by journald. Cap its size in /etc/systemd/journald.conf by setting SystemMaxUse=500M, then run sudo systemctl restart systemd-journald.
Freeing space without breaking services
Do not delete a log file that a running service is writing to. The service keeps writing to the deleted file, and the space is not released. To empty an active log, truncate it:
sudo truncate -s 0 /var/log/myapp/app.logWriting a threshold check for space and inodes
This script warns when any real filesystem reaches a given percentage of blocks or inodes. Save it as /usr/local/bin/check-disk.sh and make it executable with chmod +x:
#!/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
doneRunning the check on a schedule
Add this line with sudo crontab -e to run the check every 15 minutes and send warnings to the system log:
*/15 * * * * /usr/local/bin/check-disk.sh 85 2>&1 | logger -t check-diskReserved blocks and how ext4, XFS, and Btrfs differ
ext4 reserves 5 percent of blocks for root by default, so a full ext4 disk can still leave root some room. Check the reserve with sudo tune2fs -l /dev/sda1 | grep -i 'reserved block count'. XFS allocates inodes as needed, so inode exhaustion is rare. Btrfs reports space differently. Use btrfs filesystem usage / instead of df for accurate numbers.
Tracking growth and planning capacity
Record usage daily so you can estimate when a disk will fill. Run this from cron once a day:
echo "$(date +%F) $(df --output=used -B1 / | tail -n 1)" >> /var/log/disk-trend.logCompare the first and last values over a week. Divide the free space by the daily growth to estimate the days remaining.
Exercise
A server's ext4 root disk is 92 percent full, and du shows far less usage than df. What command finds the deleted files still held open, and what does a non-empty result mean?
Show answer
Run sudo lsof -nP +L1. A non-empty result lists deleted files that a process still holds open. Their space stays allocated until that process closes them or restarts.