From 6c0c347db28783a3412c72bf9b7ef18b9926e8e1 Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Fri, 9 Jun 2017 23:32:36 +1200 Subject: Make dub(1df) smarter, add a caveat --- bin/dub.sh | 26 +++++++++++--------------- man/man1/dub.1df | 4 ++++ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/bin/dub.sh b/bin/dub.sh index f42c5ac9..41ef88d3 100644 --- a/bin/dub.sh +++ b/bin/dub.sh @@ -1,4 +1,5 @@ # List the biggest files in a directory +self=dub # First optional argument is the directory, defaulting to the # current dir; second optional argument is the number of files to @@ -8,21 +9,16 @@ dir=${1:-.} lines=${2:-10} # Enter the target dir or bail cd -- "$dir" || exit -# Add files matching glob, shift them off if unexpanded (first and -# only entry doesn't exist) -set -- * -[ -e "$1" ] || shift - -# Add dot files, shift off the "." and ".." entries (sh(1) -# implementations seem to vary on whether they include these) -set -- .* "$@" -[ -e "$1" ] || shift -[ "$1" = . ] && shift -[ "$1" = .. ] && shift - -# Run du(1) with POSIX compatible flags -k for kilobyte unit and -# -s for total over the arguments -du -ks -- "$@" | +# 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 | diff --git a/man/man1/dub.1df b/man/man1/dub.1df index 52900a36..69a4c8e0 100644 --- a/man/man1/dub.1df +++ b/man/man1/dub.1df @@ -15,6 +15,10 @@ lists the biggest entries in a given directory, defaulting to the current directory. It defaults to printing 10 entries unless a second argument is given. +.SH CAVEATS +Skips filenames with newlines in them with an explicit warning to stderr, for +the least dangerous POSIX-compatible approach. Even so, you probably shouldn't +use this in critical scripts. .SH SEE ALSO du(1) .SH AUTHOR -- cgit v1.2.3