Checking Disk Usage and Free Space
A full disk is one of the most common causes of server outages. When a file system has no free space left, databases stop accepting writes, uploads fail, log lines are lost and even logging in can break, because many programs need to write a small file to start. Checking disk space is therefore one of the first jobs automated with Bash: a script asks how full each file system is, warns before it is too late and, when space is short, finds out what is using it.
Two standard commands answer the two different questions:
df("disk free") asks the file system itself: how big is it, how much is used and how much is still available?du("disk usage") walks through folders and adds up how much space the files in them occupy.
df tells you that a disk is filling up; du tells you where the space went. This lesson explains both, the numbers they report, the reasons those numbers sometimes disagree, and then builds a monitoring script that checks every file system and points at the largest folders.
Understanding File Systems, Blocks and Inodes
A disk (or a partition of it) is formatted with a file system, such as ext4 or XFS, and then mounted at a folder, its mount point. The root file system is mounted at /; another disk might be mounted at /mnt/data or /var/lib/mysql. Every path on the system belongs to exactly one mounted file system, so "is the disk full?" really means "is the file system that holds this path full?".
A file system runs out of two separate resources:
- Blocks hold file contents. The space figures in
dfcount blocks. - Inodes hold the information about each file (owner, permissions, times, where its blocks are). Every file, folder and symbolic link needs one inode. Many file systems, including ext4, create a fixed number of inodes when they are formatted.
A folder with millions of tiny files (cache entries, session files, mail queue files) can use up every inode while plenty of blocks are still free. New files then fail with the same "No space left on device" error as a disk that is really full. A disk check must therefore look at both.
Checking Free Space with df
Without arguments, df lists every mounted file system. The -h option ("human-readable") prints sizes with K, M, G and T suffixes in powers of 1024:
df -h /mnt/data
Filesystem Size Used Avail Use% Mounted on
/dev/loop0 60M 24K 55M 1% /mnt/data
The columns are:
| Column | Meaning |
|---|---|
Filesystem | the device or source that holds the file system |
Size | total size of the file system |
Used | space used by files and folders |
Avail | space that ordinary users can still use |
Use% | used space as a percentage |
Mounted on | the mount point |
Giving a path, as here, shows only the file system that contains that path. df -h . is the quickest way to answer "how much room is there where I am?".
Why Used plus Avail is less than Size
In the output above, the file system is 60M in size, 24K is used, yet only 55M is available. The missing space is reserved. By default, ext4 sets aside 5% of its blocks that only the root user can use, so that system services running as root can still write logs and an administrator can still log in and clean up when ordinary users have filled the disk. tune2fs -l shows the setting for an ext4 file system:
tune2fs -l disk.img | grep -E 'Block count|Reserved block count|Block size'
Block count: 16384
Reserved block count: 819
Block size: 4096
819 of 16384 blocks is 5%, about 3.2 MiB. (A small part of the remaining difference is file system metadata.) To see the effect, an ordinary user (nobody) fills the disk until it fails, and then root writes another megabyte:
setpriv --reuid=nobody --regid=nogroup --clear-groups \
bash -c 'head -c 100M /dev/zero > /mnt/data/user/fill.dat; echo "nobody: status $?"'
df -h /mnt/data
head -c 1M /dev/zero > /mnt/data/root-can-write.dat; echo "root: status $?"
head: error writing 'standard output': No space left on device
nobody: status 1
Filesystem Size Used Avail Use% Mounted on
/dev/loop0 60M 55M 0 100% /mnt/data
root: status 0
df reports 100% and 0 available, because Use% is calculated as Used ÷ (Used + Avail), rounded up, and does not count the reserved blocks as available. Root can still write into the reserve. This is why a disk can show 100% in df while root-owned services keep running for a while, and why ordinary users hit errors first.
Useful df Options
| Option | Effect |
|---|---|
-h | sizes in powers of 1024 (K, M, G) |
-H | sizes in powers of 1000 (k, M, G), as disk vendors count |
-T | add a Type column (ext4, xfs, tmpfs ...) |
-i | show inodes instead of blocks |
-l / --local | only local file systems, not network mounts |
-x TYPE | exclude a file system type, for example -x tmpfs |
-t TYPE | only show this file system type |
-P | POSIX output format: one line per file system, 1024-byte blocks |
--output=FIELDS | choose the columns (GNU df) |
tmpfs and devtmpfs file systems live in memory and are usually excluded from disk checks; on many systems they make up half of the df list.
Checking Inodes with df -i
The test file system /mnt/data was created with only 2000 inodes. The script inodes.sh creates empty files in a loop until it fails:
df -h /mnt/data
mkdir /mnt/data/many
i=0
while : > "/mnt/data/many/f$i"; do i=$((i + 1)); done
echo "created $i files"
df -h /mnt/data
df -i /mnt/data
Filesystem Size Used Avail Use% Mounted on
/dev/loop0 60M 28K 55M 1% /mnt/data
inodes.sh: line 4: /mnt/data/many/f1987: No space left on device
created 1987 files
Filesystem Size Used Avail Use% Mounted on
/dev/loop0 60M 68K 55M 1% /mnt/data
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/loop0 2000 2000 0 100% /mnt/data
Only 1987 files fit, not 2000, because the root folder, lost+found, the folders user and many and a few inodes ext4 reserves for itself already had one each. df -h reports a file system that is 1% full, yet no new file can be created. Only df -i shows the real problem: IUse% is 100%. Some file systems, such as Btrfs, allocate inodes dynamically and show - or 0 in these columns; for them the inode check does not apply.
Output That Scripts Can Read
The default df output is meant for people: older versions put a long device name on a line of its own, and the column positions change with the options. For scripts, choose the columns with --output so the format is fixed:
df --output=pcent,ipcent,avail,target /mnt/data "/mnt/backup disk"
Use% IUse% Avail Mounted on
86% 1% 8144 /mnt/data
1% 97% 26056 /mnt/backup disk
Without -h, sizes are in 1024-byte blocks. The mount point is placed last on purpose: a mount point can contain spaces, and when read splits a line into variables, the last variable receives the rest of the line, spaces included:
df --output=pcent,target / /mnt/data | tail -n +2 |
while read -r pcent target; do
echo "$target is ${pcent%\%} percent full"
done
/ is 29 percent full
/mnt/data is 86 percent full
tail -n +2 skips the header line, and ${pcent%\%} removes the trailing percent sign so the value can be compared as a number. Note that --output and -P cannot be combined; GNU df refuses with "options -P and --output are mutually exclusive". On systems without GNU df (macOS, BSD), use df -P and pick fields with awk, keeping in mind that awk fields break on mount points with spaces.
Finding What Uses the Space with du
du walks a folder tree and adds up the space used by the files in it. The following examples use a project folder with source files, logs, a cache and a hidden .git folder.
Totals and per-folder sizes
du -sh project
4.9M project
-s ("summarize") prints only the total for each argument, and -h makes it human-readable. To see which subfolder is responsible, limit the depth with -d 1 (--max-depth=1):
du -h -d 1 project
56K project/src
1.2M project/cache
788K project/.git
2.9M project/logs
4.9M project
du prints folders in the order it finds them, which is not useful for finding the biggest. sort -h sorts human-readable sizes correctly (it knows that 1.2M is more than 788K), and -r reverses the order so the largest comes first:
du -h -d 1 project | sort -hr | head -3
4.9M project
2.9M project/logs
1.2M project/cache
The first line is always the total for the folder itself. Running the same command again one level deeper (du -h -d 1 project/logs | sort -hr) is the standard way to "drill down" until you find the files responsible.
Hidden files and du -sh *
A common shortcut is du -sh * inside a folder. The glob * does not match names that start with a dot, so hidden folders are left out:
cd project
du -sh *
du -sh .[!.]*
4.0K README.md
1.2M cache
2.9M logs
56K src
788K .git
The first command printed the first four lines; .git, often one of the largest folders in a project, appeared only with the pattern .[!.]*, which matches names that start with a dot followed by anything except a second dot (so . and .. are not included). du -h -d 1 . avoids the problem entirely because it lists every subfolder, hidden or not.
Disk usage versus apparent size
du normally reports disk usage: the blocks actually allocated to a file. --apparent-size reports the file's length in bytes, which is what ls -l shows. For most files the two are close. For sparse files, files with large regions that were never written, they are very different:
truncate -s 1G project/cache/sparse.img
ls -lh project/cache/sparse.img
du -h project/cache/sparse.img
du -h --apparent-size project/cache/sparse.img
-rw-r--r-- 1 root root 1.0G Nov 24 14:53 project/cache/sparse.img
0 project/cache/sparse.img
1.0G project/cache/sparse.img
The file claims to be 1 GiB long but occupies no blocks. Virtual machine disk images, database files and the copy-truncated logs from lesson 165 are often sparse. For questions about free space, the default disk usage is the number that matters. Small files work the other way: a 2-byte file still uses one whole block, which is why README.md above shows 4.0K.
Other useful du options
| Option | Effect |
|---|---|
-s | one total per argument |
-h | human-readable sizes |
-d N | show folders down to depth N |
-a | include files, not only folders |
-c | add a grand total line for several arguments |
-x | stay on one file system; do not descend into other mounts |
--exclude=PATTERN | skip matching files and folders |
--inodes | count inodes (files and folders) instead of space (GNU du) |
--apparent-size | file lengths instead of allocated blocks |
-x is important when you search from /: without it, du -sh / also adds up every other disk mounted below /, including network shares, which can take a very long time and answers the wrong question. --inodes is the du counterpart of df -i and finds the folder holding millions of small files. du counts a file with several hard links only once.
Finding Large Files with find
When the culprit is a few large files rather than a folder, find can search by size. -size +500k means "larger than 500 KiB"; the suffixes are k, M and G. GNU find's -printf prints the size in bytes and the path, sort -nr sorts the numbers, and numfmt converts the first field to human-readable form:
find project -type f -size +500k -printf '%s\t%p\n' | sort -nr | numfmt --to=iec --field=1
1.0G project/cache/sparse.img
2.9M project/logs/app.log
1.2M project/cache/blob.bin
782K project/.git/pack
%s is the apparent size, so the sparse file appears at the top even though it uses no disk space. To rank files by the space they really occupy, use %k (disk usage in KiB) instead of %s, together with numfmt --from-unit=1024. Add -xdev to keep find on one file system, the same as du -x.
When df and du Disagree
Sometimes df reports a nearly full disk, but du over the whole file system adds up to much less. The most common reason is the one explained in lesson 165: a file was deleted while a program still had it open. The name is gone, so du cannot see it, but the blocks are freed only when the last program closes the file, so df still counts them.
The following script writes a 20 MiB log, keeps it open in a background process, deletes it, and watches the free space:
cd "/mnt/backup disk"
avail() { df -h --output=avail . | tail -1; }
echo "free at start: $(avail)"
head -c 20M /dev/urandom > big.log
echo "after writing big.log: $(avail)"
( exec 3>>big.log; sleep 2 ) & # a "program" that keeps big.log open
holder=$!
sleep 0.5
rm -- big.log
echo "after rm big.log: $(avail)"
echo "du of the folder: $(du -sh . | cut -f1)"
find /proc/[0-9]*/fd -lname '*(deleted)' -printf '%p -> %l\n' 2>/dev/null
wait "$holder"
echo "after the program ended: $(avail)"
free at start: 26M
after writing big.log: 5.5M
after rm big.log: 5.5M
du of the folder: 44K
/proc/714/fd/3 -> /mnt/backup disk/big.log (deleted)
after the program ended: 26M
After rm, du sees only 44K in the folder, but df still shows 5.5M free. The find command looks through /proc/PID/fd, where Linux shows every open file descriptor of every process as a symbolic link; a link target that ends in (deleted) is a deleted file still held open. Here process 714 holds it on descriptor 3. Space came back only when that process exited. On a real server, the fix is to restart or signal the program so it closes the file (or, as an emergency measure, truncate it through the descriptor with : > /proc/PID/fd/N). If lsof is installed, lsof +L1 lists the same files.
Other reasons for a difference are the reserved blocks described earlier, files hidden underneath a mount point (written to /mnt/data before a disk was mounted there, invisible to du while the disk is mounted), and, on file systems such as Btrfs and ZFS, snapshots that keep old blocks alive.
A Complete Example: A Disk Space Monitor
disk-check.sh checks space and inodes on every local file system, or on the mount points given as arguments. It reports each file system as OK, WARNING or CRITICAL, can list the folders responsible, and returns an exit status that monitoring tools understand.
#!/usr/bin/env bash
#
# disk-check.sh - warn when file systems run low on space or inodes
#
# Usage: disk-check.sh [-w WARN] [-c CRIT] [-t TOP] [MOUNT_POINT...]
# -w WARN warning level in percent used (default: 80)
# -c CRIT critical level in percent used (default: 90)
# -t TOP for file systems at WARN or above, list the TOP folders under
# the mount point that use the most space or inodes (default: 0 = off)
# Without MOUNT_POINT, every local file system except tmpfs, devtmpfs,
# squashfs and overlay is checked. Space and inodes are both checked.
#
# Exit status (monitoring convention): 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN
set -uo pipefail
warn=80 crit=90 top=0
status=0 # worst level seen so far
labels=(OK WARNING CRITICAL UNKNOWN)
usage() {
echo "usage: ${0##*/} [-w WARN] [-c CRIT] [-t TOP] [MOUNT_POINT...]" >&2
exit 3
}
# raise LEVEL: remember LEVEL if it is worse than the current status
raise() { (( $1 > status )) && status=$1; return 0; }
# level PERCENT: print 0 (OK), 1 (WARNING) or 2 (CRITICAL)
level() {
if (( $1 >= crit )); then echo 2
elif (( $1 >= warn )); then echo 1
else echo 0
fi
}
# show_top MOUNT space|inodes: the TOP folders that use the most space or
# the most inodes, staying on this file system (-x)
show_top() {
local -a how=(-h)
local order=-hr
if [[ $2 == inodes ]]; then how=(--inodes); order=-nr; fi
timeout 120 du -x "${how[@]}" -d 1 -- "$1" 2>/dev/null |
sort "$order" | sed -n "2,$(( top + 1 ))p" | sed 's/^/ /'
}
while getopts ':w:c:t:' opt; do
case $opt in
w) warn=$OPTARG ;;
c) crit=$OPTARG ;;
t) top=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
for n in "$warn" "$crit" "$top"; do
[[ $n =~ ^[0-9]{1,3}$ ]] || { echo "${0##*/}: not a whole number: '$n'" >&2; exit 3; }
done
warn=$((10#$warn)) crit=$((10#$crit)) top=$((10#$top))
(( warn < crit && crit <= 100 )) || { echo "${0##*/}: need WARN < CRIT <= 100" >&2; exit 3; }
df_args=(--output=pcent,ipcent,avail,target)
if (( $# > 0 )); then
df_args+=(-- "$@")
else
df_args+=(--local -x tmpfs -x devtmpfs -x squashfs -x overlay)
fi
errors=$(mktemp) || exit 3
trap 'rm -f -- "$errors"' EXIT
# The mount point is the last column, so `read` keeps any spaces in it.
while read -r pcent ipcent avail target; do
pcent=${pcent%\%} ipcent=${ipcent%\%}
[[ $ipcent =~ ^[0-9]+$ ]] || ipcent=0 # "-": no inode limit
space_level=$(level "$pcent")
inode_level=$(level "$ipcent")
lvl=$(( space_level > inode_level ? space_level : inode_level ))
raise "$lvl"
free=$(numfmt --from-unit=1024 --to=iec "$avail")
printf '%-8s %s: space %d%% used (%s free), inodes %d%% used\n' \
"${labels[lvl]}" "$target" "$pcent" "$free" "$ipcent"
if (( lvl > 0 && top > 0 )); then
if (( inode_level > space_level )); then
echo " folders with the most inodes:"
show_top "$target" inodes
else
echo " largest folders:"
show_top "$target" space
fi
fi
done < <(df "${df_args[@]}" 2>"$errors" | tail -n +2)
if [[ -s $errors ]]; then
sed 's/^/UNKNOWN /' "$errors"
raise 3
fi
exit "$status"
How It Works
- Exit status convention. Monitoring systems such as Nagios, Icinga and their many compatible tools run a check script and read its exit status: 0 for OK, 1 for WARNING, 2 for CRITICAL and 3 for UNKNOWN (the check itself could not run properly). The script follows that convention, so a usage error also exits with 3. The variable
statuskeeps the worst level seen, andraiseupdates it;raiseends withreturn 0so that a comparison that is false does not become the function's status. - Validation. All three numbers must be one to three digits, are read as decimal with
10#(so08is not treated as octal), and the warning level must be below the critical level. - Choosing file systems. With arguments,
dfchecks exactly those paths, and--stops a path starting with-from being read as an option. Without arguments,--localskips network mounts and-xremoves memory-based and read-only image file systems, which would only produce noise. - Reading df safely.
--outputfixes the columns, the mount point comes last soreadkeeps spaces in it,tail -n +2removes the header, and the loop reads from process substitution (lesson 151) so thatstatusis still set after the loop. Errors fromdf, such as a path that does not exist, go to a temporary file;dfstill prints the paths that worked, and afterwards the script reports each error as UNKNOWN. - Two checks per file system. Each line gets a level for space and a level for inodes, and the worse of the two decides the label. A file system with 97% of its inodes used is CRITICAL even if its space is almost empty.
- Pointing at the cause. With
-t, for every file system at WARNING or above,show_toprunsdu -x -d 1on the mount point (-xkeeps it from crossing into other mounts) and prints the TOP largest folders. If inodes are the bigger problem, it counts inodes withdu --inodesinstead, because the folder with the most files is often small in size.timeout 120keeps a slowduon a huge or hung file system from blocking the check forever.sed -n "2,$((top + 1))p"skips the first sorted line, which is the total for the mount point itself.
Running the Complete Example
The test machine has two small extra disks: /mnt/data, which is 86% full, and /mnt/backup disk (with a space in its name), which has almost no data but 960 small files on a file system created with about 1000 inodes.
$ disk-check.sh / /mnt/data /mnt/backup\ disk
OK /: space 29% used (30G free), inodes 2% used
WARNING /mnt/data: space 86% used (8.0M free), inodes 1% used
CRITICAL /mnt/backup disk: space 1% used (26M free), inodes 97% used
status 2
The overall status is 2 because the worst result was CRITICAL. Raising the thresholds changes the verdict for /mnt/data:
$ disk-check.sh -w 90 -c 95 /mnt/data
OK /mnt/data: space 86% used (8.0M free), inodes 1% used
status 0
With -t 3, the script shows where to look. For /mnt/data it lists the largest folders; for /mnt/backup disk, where inodes are the problem, it lists the folders with the most inodes:
$ disk-check.sh -t 3 /mnt/data /mnt/backup\ disk
WARNING /mnt/data: space 86% used (8.0M free), inodes 1% used
largest folders:
31M /mnt/data/uploads
16M /mnt/data/db
2.1M /mnt/data/tmp
CRITICAL /mnt/backup disk: space 1% used (26M free), inodes 97% used
folders with the most inodes:
961 /mnt/backup disk/daily
1 /mnt/backup disk/lost+found
status 2
A path that does not exist and invalid options are reported as UNKNOWN (status 3):
$ disk-check.sh / /missing
OK /: space 29% used (30G free), inodes 2% used
UNKNOWN df: /missing: No such file or directory
status 3
$ disk-check.sh -w 90 -c 80 /
disk-check.sh: need WARN < CRIT <= 100
status 3
$ disk-check.sh -w abc /
disk-check.sh: not a whole number: 'abc'
status 3
$ disk-check.sh -x /
usage: disk-check.sh [-w WARN] [-c CRIT] [-t TOP] [MOUNT_POINT...]
status 3
Run without arguments, the script checks every local disk-based file system that df lists on the machine. Because the result is an exit status plus a short text, the same script can be run by hand, called from a monitoring system, or scheduled with cron (lesson 170) together with a notification step (lesson 173), for example disk-check.sh -t 5 > /tmp/disk.txt || notify-admin /tmp/disk.txt, where notify-admin stands for whatever sends the message.