aboutsummaryrefslogtreecommitdiff
path: root/bin/chc.sh
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2017-04-05 20:06:39 +1200
committerTom Ryder <tom@sanctum.geek.nz>2017-04-05 20:46:47 +1200
commitc8ab406749124d2e762ad5cf53963070113afd0f (patch)
tree54c9721a06957ebe7098a211eea803b0230c0f5d /bin/chc.sh
parentHandle POSIX correctness in ~/.bash_profile (diff)
downloaddotfiles-c8ab406749124d2e762ad5cf53963070113afd0f.tar.gz
dotfiles-c8ab406749124d2e762ad5cf53963070113afd0f.zip
Apply runtime shebanging to POSIX shell
Diffstat (limited to 'bin/chc.sh')
-rw-r--r--bin/chc.sh30
1 files changed, 30 insertions, 0 deletions
diff --git a/bin/chc.sh b/bin/chc.sh
new file mode 100644
index 00000000..8b15317c
--- /dev/null
+++ b/bin/chc.sh
@@ -0,0 +1,30 @@
+# 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"