style(user/bknpass):Simplify boilerplate
[BK-2020-03.git] / unitproc / bkt-read_stdin
CommitLineData
335b71e1
SBS
1#!/usr/bin/env bash
2# Desc: Reads stdin
3
4yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
5die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
6must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
7read_stdin() {
8 # Desc: Consumes stdin; outputs as stdout lines
9 # Input: stdin (consumes)
c06f074c
SBS
10 # Output: stdout (newline delimited)
11 # return 0 stdin read
12 # return 1 stdin not present
335b71e1 13 # Example: printf "foo\nbar\n" | read_stdin
c06f074c 14 # Depends: GNU bash (version 5.1.16), GNU Coreutils 8.32 (cat)
c737bccf 15 # Version: 0.1.1
c06f074c 16 # Attrib: Steven Baltakatei Sandoval (2024-01-29). reboil.com
335b71e1
SBS
17 local input_stdin output;
18
19 # Store stdin
20 if [[ -p /dev/stdin ]]; then
c737bccf
SBS
21 input_stdin="$(cat -)" || {
22 echo "FATAL:Error reading stdin." 1>&2; return 1; };
c06f074c
SBS
23 else
24 return 1;
335b71e1
SBS
25 fi;
26
27 # Store as output array elements
28 ## Read in stdin
29 if [[ -n $input_stdin ]]; then
30 while read -r line; do
31 output+=("$line");
c737bccf
SBS
32 done < <(printf "%s\n" "$input_stdin") || {
33 echo "FATAL:Error parsing stdin."; return 1; };
335b71e1
SBS
34 fi;
35
36 # Print to stdout
37 printf "%s\n" "${output[@]}";
c06f074c
SBS
38
39 return 0;
335b71e1 40}; # read stdin to stdout lines
335b71e1 41
c06f074c 42yell "WARNING:This is a Bash function definition for read_stdin.";