~mikini/hometools

ref: 30788f6c0c43145289eb9955bfc9fc155afd15b9 hometools/stop_watch -rwxr-xr-x 1.8 KiB
30788f6c — Mikkel Kirkgaard Nielsen stop_watch: Fix parsing of H, M & S to only include remainder 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#! /bin/bash

# Show a counting summary of elapsed time since invocation of the script, or some
# arbitrary start date in the past given as argument. Argument can be a free
# form date parsable by GNU coreutils (see 'info coreutils "Date input formats"').

FAIL=0

# print a textual representation of the elapsed time between the Unix Epoch
# timestamps given as parameters as days, hours, minutes, seconds
function print_elapsed () {
    SECONDS_PR_MINUTE=60
    SECONDS_PR_HOUR=$((60*$SECONDS_PR_MINUTE))
    SECONDS_PR_DAY=$((24*$SECONDS_PR_HOUR))

    ELAPSED=$(($2-$1))
    ELAPSED_D=$(($ELAPSED/$SECONDS_PR_DAY))
    ELAPSED_REMAINDER=$(($ELAPSED-$ELAPSED_D*$SECONDS_PR_DAY))
    ELAPSED_H=$(($ELAPSED_REMAINDER/$SECONDS_PR_HOUR))
    ELAPSED_REMAINDER=$(($ELAPSED_REMAINDER-$ELAPSED_H*$SECONDS_PR_HOUR))
    ELAPSED_M=$(($ELAPSED_REMAINDER/$SECONDS_PR_MINUTE))
    ELAPSED_S=$(($ELAPSED_REMAINDER-$ELAPSED_M*$SECONDS_PR_MINUTE))
    # TODO: ISO period should be printed in a fixed width box of 2 characters
    echo -n "$ELAPSED_D days, $ELAPSED_H:$ELAPSED_M:$ELAPSED_S (P${ELAPSED_D}DT${ELAPSED_H}H${ELAPSED_M}M${ELAPSED_S}S)"
}

function exith () {
    STOP=$(date +%s)
    if [ ! $FAIL -eq 1 ]; then
	echo -e "\nStop : $(date -d @$STOP) ($STOP)"
	echo -n "Elapsed from start to stop: "
	print_elapsed $START $STOP
    fi
}

trap exith EXIT

if [ -z "$1" ]; then
    START=$(date +%s)
else
    START=$(date +%s --date "$1")
    if [ $? -eq 1 ]; then
	echo "Invalid start date argument: $START. Supply no argument for current time. Aborting."
	FAIL=1
	exit 27
    fi
fi

echo -en "Start: $(date -d @$START) ($START)\n"
while true; do
    NOW=$(date +%s)
    echo -en "\e[GNow  : $(date -d @$NOW), elapsed: "
    print_elapsed $START $NOW
    echo -n "      " # remove potential leftovers from 23:59:59 -> 0:0:0 times two
    sleep 1
done