#!/bin/sh
#
# dub - list the biggest files in a directory (default: 10 entries)
# usage:
#   dub /path
#   dub /path 20

self=dub

# first optional argument is the directory, defaulting to the
# current dir; second optional argument is the number of files to
# show, defaulting to 20
dir="${1:-.}"
lim="${2:-10}"

# enter the target dir or bail
cd -- "${dir}" || exit

# some find(1) devilry to deal with newlines as safely as possible.
# the idea is not even to touch them, and warn about their presence;
# better the results are wrong than malformed
nl=$(printf '\n/')
find . ! -name . -prune \( \
  -name '*'"${nl%/}"'*' \
  -exec sh -c '
      printf >&2 '\''%s: warning: skipped newline filename\n'\'' "$1"
  ' _ "${self}" \; \
  -o -exec du -ksx -- {} + \) \
  |
  # sort the first field (the sizes) numerically, in reverse
  sort -k1,1nr \
  |
  # limit the output to the given number of lines
  awk -v lim="${lim}" 'NR <= lim'
