Report the Largest Files Under a Tree

Scan a directory tree, sort files by size, and print the largest offenders so disk pressure can be investigated quickly.

BashCli Tooling

Code

bashsnippet
15 lines
#!/usr/bin/env bash
set -euo pipefail

readonly ROOT="${1:-.}"
readonly TOP_N="${2:-10}"

if [[ ! -d "${ROOT}" ]]; then
  echo "not a directory: ${ROOT}" >&2
  exit 2
fi

find "${ROOT}" -type f -size +10M -print0 \
  | xargs -0 du -h 2>/dev/null \
  | sort -rh \
  | head -n "${TOP_N}"

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1.0K	.

Walking the tree and collecting sizes

The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.

The work is delegated to readonly and find, chained through 3 pipes so each stage’s output feeds the next.

The script leans on parameter expansion 6 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

What to watch for

  • The pipeline is 3 stages deep — when it misbehaves, split the pipe and test the stages separately.

Statements that matter

| xargs -0 du -h 2>/dev/null \
| sort -rh \
| head -n "${TOP_N}"

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `find` must be available on the PATH environment variable; everything else is shell built-in syntax.