aboutsummaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2016-12-09 10:16:05 +1300
committerTom Ryder <tom@sanctum.geek.nz>2016-12-09 10:17:34 +1300
commita0acd17ec7a54b2e2fe48b1a98fc7f99cf0d0341 (patch)
tree41bb0d54b40c79ab3f79d4d927c4fd8dd07171c6 /bin
parentAdd uts(1df) (diff)
downloaddotfiles-a0acd17ec7a54b2e2fe48b1a98fc7f99cf0d0341.tar.gz
dotfiles-a0acd17ec7a54b2e2fe48b1a98fc7f99cf0d0341.zip
Add chc(1df)
Diffstat (limited to 'bin')
-rwxr-xr-xbin/chc31
1 files changed, 31 insertions, 0 deletions
diff --git a/bin/chc b/bin/chc
new file mode 100755
index 00000000..b1e4000d
--- /dev/null
+++ b/bin/chc
@@ -0,0 +1,31 @@
+#!/bin/sh
+# Cache the output of a command and emit it straight from the cache if not
+# expired on each run
+
+# First argument is the cache path, second is the duration in seconds
+cac=$1 dur=$2
+shift 2
+
+# Get the current timestamp with uts(1df)
+uts=$(uts) || exit
+
+# Function checks cache exists, is readable, and not expired
+fresh() {
+ [ -f "$cac" ] || return
+ [ -r "$cac" ] || return
+ exp=$(sed 1q -- "$cac") || return
+ [ "$((exp > uts))" -eq 1 ]
+}
+
+# Write runs the command and writes it to the cache
+write() {
+ exp=$((uts + dur))
+ printf '%u\n' "$exp"
+ "$@"
+}
+
+# If the cache isn't fresh, try to write a new one, or bail out
+fresh "$cac" || write "$@" > "$cac" || exit
+
+# Emit the content (exclude the first line, which is the timestamp)
+sed 1d -- "$cac"