Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Created November 27, 2018 09:37
Show Gist options
  • Save kou1okada/078e39d4d14f61ed1f685be34e5cf507 to your computer and use it in GitHub Desktop.
Save kou1okada/078e39d4d14f61ed1f685be34e5cf507 to your computer and use it in GitHub Desktop.
lapdu - Lap for du.
#!/usr/bin/env bash
#
# Lap for du.
# Copyright (c) 2018 Koichi OKADA. All rights reserved.
# This script is destributed under the MIT license.
#
source hhs.bash 0.2.0
function init_lapdu ()
{
: ${OPT_INTERVAL:=5}
: ${OPT_SCALE:=1000000}
: ${OPT_UNIT:=MB}
: ${OPT_WIDTH:=5.1}
}
function optparse_lapdu ()
{
case "$1" in
-i|--interval) # <interval>
# Set lap intervals for du in seconds.
# Default is 5 seconds.
nparams 1
optset INTERVAL "$2"
;;
-u|--unit) # <unit>
# Set unit for byte size.
# <unit> can take /([kMGT]|Ki|Mi|Gi|Ti)B?|B/.
# Default is MB.
nparams 1
case "${2,,}" in
b) optset UNIT B ; optset SCALE 1 ;;
k|kb) optset UNIT kB ; optset SCALE $(( 1000 ** 1 )) ;;
m|mb) optset UNIT MB ; optset SCALE $(( 1000 ** 2 )) ;;
g|gb) optset UNIT GB ; optset SCALE $(( 1000 ** 3 )) ;;
t|tb) optset UNIT TB ; optset SCALE $(( 1000 ** 4 )) ;;
ki|kib) optset UNIT KiB ; optset SCALE $(( 1024 ** 1 )) ;;
mi|mib) optset UNIT MiB ; optset SCALE $(( 1024 ** 2 )) ;;
gi|gib) optset UNIT GiB ; optset SCALE $(( 1024 ** 3 )) ;;
ti|tib) optset UNIT TiB ; optset SCALE $(( 1024 ** 4 )) ;;
*)
error "Unknown unit for byte size: $2"
eixt 1
;;
esac
;;
-w|--width) # <width>
# Set width and precision for template of printf.
# Default is `5.1`.
nparams 1
optset WIDTH "$2"
if ! [[ "$2" =~ ^[0-9]+\.[0-9]+$ ]]; then
error "Invalidh format of width: $2"
exit 1
fi
;;
*) return 1 ;;
esac
}
function lapdu () # [<options>] [<params> ...]
# Lap for du.
# Params:
# Params will be passed to `du`.
# Note, however, that options for `du` must be placed after `--`.
{
local i
while true; do
(( 1 < i++ )) && sleep "${OPT_INTERVAL:-5}";
du -bc "$@" \
| tail -n1
done \
| awk -vscale="$OPT_SCALE" -vunit="$OPT_UNIT" -vwidth="${OPT_WIDTH%%.*}" -vprecision="${OPT_WIDTH##*.}" \
'
function getstamp(_t){
cmd = "date +%s.%N";
cmd | getline _t; close(cmd);
return 0+_t;
}
{
t2 = t1; t1 = getstamp();
n2 = n1; n1 = $1;
}
0 < t2 {
delta = (n1-n2) / scale;
printf("%'\''*.*f %s (%'\''*.*f %s/s)\n", width, precision, delta, unit, width, precision, delta / (t1-t2), unit);
}
'
}
invoke_command "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment