]> zdv2.bktei.com Git - BK-2020-03.git/blob - unitproc/bkt-sum_float
e433c0a8eada1131fb6fcfea2d80d867d77fc08b
[BK-2020-03.git] / unitproc / bkt-sum_float
1 #!/bin/bash
2 # Desc: Sums newline-delimited floats received from stdin
3 # Usage: some_app | sumFloat
4 # Example: printf -- "-3\n0.14" | sumFloat
5 # Result: -2.860000
6 # Version: 0.0.1
7 # Depends: bc 1.07.1
8
9 yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
10 die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
11 must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
12 sum_float() {
13 # Check dependencies
14 if ! command -v bc 1>/dev/random 2>&1; then die "FATAL:Missing:bc"; fi;
15
16 # Store stdin
17 if [[ -p /dev/stdin ]]; then
18 input_stdin="$(cat -)" || {
19 die "FATAL:Error reading stdin."; };
20 else
21 die "FATAL:No stdin detected.";
22 fi;
23
24 # Process lines
25 local sum="0.0";
26 local re;
27 re='^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$';
28 if [[ -n $input_stdin ]]; then
29 while read -r line; do
30 if ! [[ "$line" =~ $re ]]; then die "FATAL:Not a float:${line}"; fi;
31 sum="$(printf -- "%f + %f\n" "$sum" "$line" | bc -l;)";
32 done < <(printf "%s\n" "$input_stdin") || {
33 die "FATAL:Error parsing stdin."; };
34 fi;
35
36 # Print result
37 printf "%f\n" "$sum";
38 }; # sum stdin floats
39
40 # Author: Steven Baltakatei Sandoval
41 # License: GPLv3+