Created
February 26, 2018 00:33
-
-
Save dsandler/4669662c02dd6e497d1286754e986320 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# duration - format a time interval | |
# | |
# usage: duration [flags] <seconds> | |
# or: . duration ; format_duration [flags] <seconds> | |
# | |
# flags: | |
# -l: long format ("5 days 1 second") | |
# -s: short format ("5:00:00:01") | |
# -a: approximate by only printing largest component ("5 days") | |
# | |
# [email protected] | |
# print unless zero | |
function pz() { | |
n="$1" | |
suff="$2" | |
if [ "$n" -gt 0 ]; then | |
echo "$n$suff" | |
fi | |
} | |
# pluralize word unless zero | |
function plz() { | |
n="$1" | |
w="$2" | |
suff="$3" | |
if [ "$n" -gt 0 ]; then | |
if [ "$n" -eq 1 ]; then | |
echo "$n $w$suff" | |
else | |
echo "$n ${w}s$suff" | |
fi | |
fi | |
} | |
function format_duration() { | |
while true; do | |
if [ -z "$1" -o "$1" = "-h" ]; then | |
echo "usage: duration [-l|-s] [-a] <seconds>" | |
return -1 | |
elif [ "$1" = "-l" ]; then | |
long=1 | |
shift | |
elif [ "$1" = "-s" ]; then | |
short=1 | |
shift | |
elif [ "$1" = "-a" ]; then | |
approx=1 | |
shift | |
else | |
break | |
fi | |
done | |
d="$1" | |
str="" | |
#((ms=$d % 1000)) | |
#((d=$d / 1000)) | |
((s=$d % 60)) | |
((d=$d / 60)) | |
((m=$d % 60)) | |
if [ "$approx" = "1" -a "$m" -gt 0 ]; then s=0; fi | |
((d=$d / 60)) | |
((h=$d % 24)) | |
if [ "$approx" = "1" -a "$h" -gt 0 ]; then m=0; fi | |
((d=$d / 24)) | |
if [ "$approx" = "1" -a "$d" -gt 0 ]; then h=0; fi | |
if [ "$long" = "1" ]; then | |
echo "$(plz $d day ' ')$(plz $h hour ' ')$(plz $m minute ' ')$(plz $s second)" | |
elif [ "$short" = "1" ]; then | |
printf "%s%02d:%02d:%02d\n" "$(pz $d :)" $h $m $s | |
else | |
echo "$(pz $d d)$(pz $h h)$(pz $m m)$(pz $s s)" | |
fi | |
} | |
# if running the file directly instead of sourcing, invoke function | |
if [ "$0" = "$BASH_SOURCE" ]; then | |
format_duration "$@" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment