Shows the N largest immediate subdirectories of a path, human-readable, biggest first. The fast first step when a disk is unexpectedly full.
#!/usr/bin/env bash
# Show the top N largest immediate subdirectories in a path.
# Usage: disk-usage-top.sh <path> [N] (requires GNU or BSD `du`/`sort -h`)
set -euo pipefail
target="$1"
n="${2:-10}"
if [ ! -d "$target" ]; then
echo "not a directory: $target" >&2
exit 1
fi
du -h -d 1 -- "$target" 2>/dev/null | sort -rh | head -n "$n"
| path | string — positional argument, directory to scan one level deep, e.g. /var |
|---|---|
| N | integer — optional 2nd argument, how many rows to show; defaults to 10 |
N lines of <human-size> <path>, largest subdirectory
first. Exits 1 with a message if path isn't a directory.
$ ./disk-usage-top.sh /var 5
2.1G /var/log
860M /var/cache
340M /var/lib
12M /var/tmp
4.0K /var/spool
-- before the path stops a directory name starting with - from being parsed as a du option.du/sort/head, never modifies anything it scans.