← all snippets

disk-usage-top

Shows the N largest immediate subdirectories of a path, human-readable, biggest first. The fast first step when a disk is unexpectedly full.

Bash #08

Source

disk-usage-top.sh
#!/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"

Input

pathstring — positional argument, directory to scan one level deep, e.g. /var
Ninteger — optional 2nd argument, how many rows to show; defaults to 10

Output

Prints up to N lines of <human-size> <path>, largest subdirectory first. Exits 1 with a message if path isn't a directory.

Usage

$ ./disk-usage-top.sh /var 5
2.1G    /var/log
860M    /var/cache
340M    /var/lib
12M     /var/tmp
4.0K    /var/spool

Config

No configuration required.

Security notes

  • -- before the path stops a directory name starting with - from being parsed as a du option.
  • Read-only: only runs du/sort/head, never modifies anything it scans.
  • Permission-denied subdirectories are silently skipped (stderr redirected) rather than aborting the whole scan.