bce5066c04dedaa342485f307b743931ac8f9172
[BK-2020-03.git] / user / check_order.sh
1 #!/bin/bash
2 # Desc: Checks stdin for lines out of order.
3 # Input: stdin
4 # Output: stdout
5 # Version: 0.0.1
6
7 yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
8 die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
9 must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
10 read_stdin() {
11 # Desc: Consumes stdin; outputs as stdout lines
12 # Input: stdin (consumes)
13 # Output: stdout (newline delimited)
14 # return 0 stdin read
15 # return 1 stdin not present
16 # Example: printf "foo\nbar\n" | read_stdin
17 # Depends: GNU bash (version 5.1.16), GNU Coreutils 8.32 (cat)
18 # Version: 0.1.1
19 # Attrib: Steven Baltakatei Sandoval (2024-01-29). reboil.com
20 local input_stdin output;
21
22 # Store stdin
23 if [[ -p /dev/stdin ]]; then
24 input_stdin="$(cat -)" || {
25 echo "FATAL:Error reading stdin." 1>&2; return 1; };
26 else
27 return 1;
28 fi;
29
30 # Store as output array elements
31 ## Read in stdin
32 if [[ -n $input_stdin ]]; then
33 while read -r line; do
34 output+=("$line");
35 done < <(printf "%s\n" "$input_stdin") || {
36 echo "FATAL:Error parsing stdin."; return 1; };
37 fi;
38
39 # Print to stdout
40 printf "%s\n" "${output[@]}";
41
42 return 0;
43 }; # read stdin to stdout lines
44 main() {
45 previous="";
46 n=1;
47 while IFS= read -r line; do
48 current="$line";
49 if [[ -n "$previous" ]] && [[ "$previous" > "$current" ]]; then
50 yell "STATUS:Line $n is out of order: $line";
51 fi;
52 previous="$current";
53 ((n++));
54 done < <(read_stdin || die "FATAL:No stdin.");
55 }; # main program
56 export -f read_stdin;
57
58 main "$@";
59
60 # Author: Steven Baltakatei Sandoval
61 # License: GPLv3+