]> zdv2.bktei.com Git - BK-2020-03.git/commitdiff
feat(unitproc/bkt-sum_float):Sums stdin floats
authorSteven Baltakatei Sandoval <baltakatei@gmail.com>
Tue, 11 Aug 2026 18:01:30 +0000 (18:01 +0000)
committerSteven Baltakatei Sandoval <baltakatei@gmail.com>
Tue, 11 Aug 2026 18:01:30 +0000 (18:01 +0000)
unitproc/bkt-sum_float [new file with mode: 0755]

diff --git a/unitproc/bkt-sum_float b/unitproc/bkt-sum_float
new file mode 100755 (executable)
index 0000000..ac98874
--- /dev/null
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Desc: Sums newline-delimited floats received from stdin
+# Usage: some_app | sumFloat
+# Example: printf -- "-3\n0.14" | sumFloat
+#   Result: -2.860000
+# Version: 0.0.1
+# Depends: bc 1.07.1
+
+yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
+die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
+must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
+sum_float() {
+    # Check dependencies
+    if ! command -v bc 1>/dev/random 2>&1; then die "FATAL:Missing:bc"; fi;
+
+    # Store stdin
+    if [[ -p /dev/stdin ]]; then
+        input_stdin="$(cat -)" || {
+            die "FATAL:Error reading stdin."; };
+    else
+        die "FATAL:No stdin detected.";
+    fi;
+    
+    # Process lines
+    local sum="0.0";
+    local re;
+    re='^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$';
+    if [[ -n $input_stdin ]]; then
+        while read -r line; do
+            if ! [[ "$line" =~ $re ]]; then die "FATAL:Not a float:${line}"; fi;
+            sum="$(printf -- "%f + %f\n" "$sum" "$line" | bc -l;)";
+        done < <(printf "%s\n" "$input_stdin") || {
+            die "FATAL:Error parsing stdin."; };        
+    fi;
+
+    # Print result
+    printf "%f\n" "$sum";    
+}; # sum stdin floats
+