feat(TODO.org):Add TODO list
[BK-2020-03.git] / unitproc / bktemp-timeEpochNS
CommitLineData
e9c166c0
SBS
1#!/bin/bash
2# Desc: Get timestamp in nanoseconds
3
6ed44731
SBS
4yell() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
5die() { yell "$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
6try() { "$@" || die "cannot $*"; } #o
4caeddd7 7timeEpochNS() {
e9c166c0 8 # Desc: Get epoch nanoseconds
4caeddd7 9 # Usage: timeEpochNS
d29fa44f 10 # Version 0.2.3
6ed44731 11 # Input: arg1: 'date'-parsable timestamp string (optional)
e9c166c0 12 # Output: Nanoseconds since 1970-01-01
d29fa44f 13 # Depends: date 8, cut 8, yell()
6ed44731 14 # Ref/Attrib: Force base 10 Bash arith with '10#'. https://stackoverflow.com/a/24777667
d29fa44f
SBS
15 local argTime timeCurrent timeInput timeEpochFloat timeEpochInt
16 local timeEpochNsFrac timeEpochNs
6ed44731
SBS
17
18 argTime="$1";
19
20 # Get Current Time
d29fa44f 21 timeCurrent="$(date --iso-8601=ns)"; # Produce `date`-parsable current timestamp with resolution of 1 nanosecond.
6ed44731
SBS
22
23 # Decide to parse current or supplied time
24 ## Check if time argument empty
25 if [[ -z "$argTime" ]]; then
26 ## T: Time argument empty, use current time
d29fa44f 27 timeInput="$timeCurrent";
6ed44731
SBS
28 else
29 ## F: Time argument exists, validate time
30 if date --date="$argTime" 1>/dev/null 2>&1; then
31 ### T: Time argument is valid; use it
d29fa44f 32 timeInput="$argTime";
6ed44731
SBS
33 else
34 ### F: Time argument not valid; exit
35 yell "ERROR:Invalid time argument supplied. Exiting."; exit 1;
d5f7b62e
SBS
36 fi;
37 fi;
6ed44731 38 # Construct and deliver nanoseconds since 1970-01-01
d29fa44f
SBS
39 timeEpochFloat="$(date --date="$timeInput" +%s.%N)"; # Save ssss.NNNNNNNNN
40 timeEpochInt="$(echo "$timeEpochFloat" | cut -d. -f1)"; # Get ssss
41 timeEpochNsFrac="$(echo "$timeEpochFloat" | cut -d. -f2)"; # Get NNNNNNNNN
42 timeEpochNs="$(( (10#"$timeEpochInt" * 10**9) + (10#"$timeEpochNsFrac") ))";
43 echo "$timeEpochNs";
aec895f5 44} # Nanoseconds since 1970-01-01
e9c166c0
SBS
45
46#==BEGIN sample code==
4caeddd7 47echo "It's been $(timeEpochNS) nanoseconds since 1970-01-01.";
6ed44731
SBS
48echo "It's been $(timeEpochNS "10 years ago") nanoseconds since 10 years ago.";
49echo "It's been $(timeEpochNS "2003-02-01T08:59:15-05:00") nanoseconds since contact lost with STS-107.";
e9c166c0 50#==END sample code==
5b497be8
SBS
51
52# Author: Steven Baltakatei Sandoval
53# License: GPLv3+