feat(user/check_order.sh):Add script to check alphabetical order develop
authorSteven Baltakatei Sandoval <baltakatei@gmail.com>
Sun, 30 Jun 2024 00:23:13 +0000 (00:23 +0000)
committerSteven Baltakatei Sandoval <baltakatei@gmail.com>
Sun, 30 Jun 2024 00:23:13 +0000 (00:23 +0000)
user/check_order.sh [new file with mode: 0755]

diff --git a/user/check_order.sh b/user/check_order.sh
new file mode 100755 (executable)
index 0000000..bce5066
--- /dev/null
@@ -0,0 +1,61 @@
+#!/bin/bash
+# Desc: Checks stdin for lines out of order.
+# Input: stdin
+# Output: stdout
+# Version: 0.0.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
+read_stdin() {
+    # Desc: Consumes stdin; outputs as stdout lines
+    # Input: stdin (consumes)
+    # Output: stdout  (newline delimited)
+    #         return  0  stdin read
+    #         return  1  stdin not present
+    # Example: printf "foo\nbar\n" | read_stdin
+    # Depends: GNU bash (version 5.1.16), GNU Coreutils 8.32 (cat)
+    # Version: 0.1.1
+    # Attrib: Steven Baltakatei Sandoval (2024-01-29). reboil.com
+    local input_stdin output;
+
+    # Store stdin
+    if [[ -p /dev/stdin ]]; then
+        input_stdin="$(cat -)" || {
+            echo "FATAL:Error reading stdin." 1>&2; return 1; };
+    else
+        return 1;
+    fi; 
+    
+    # Store as output array elements
+    ## Read in stdin
+    if [[ -n $input_stdin ]]; then
+        while read -r line; do
+            output+=("$line");
+        done < <(printf "%s\n" "$input_stdin") || {
+            echo "FATAL:Error parsing stdin."; return 1; };
+    fi;
+
+    # Print to stdout
+    printf "%s\n" "${output[@]}";
+
+    return 0;
+}; # read stdin to stdout lines
+main() {
+    previous="";
+    n=1;
+    while IFS= read -r line; do
+        current="$line";
+        if [[ -n "$previous" ]] && [[ "$previous" > "$current" ]]; then
+            yell "STATUS:Line $n is out of order: $line";
+        fi;
+        previous="$current";
+        ((n++));
+    done < <(read_stdin || die "FATAL:No stdin.");
+}; # main program
+export -f read_stdin;
+
+main "$@";
+
+# Author: Steven Baltakatei Sandoval
+# License: GPLv3+