college/Summer-2024/CS-3424/Quizzes/Quiz-2/even-lines-rigorous.bash

69 lines
1.2 KiB
Bash
Raw Normal View History

2024-06-23 04:09:55 -05:00
#!/usr/bin/env bash
set -eEou pipefail
die() {
printf "%s\n" "${*}"
exit 1
}
usage() {
local script
script="$(basename "${0}")"
cat <<-__EOS__
==== USAGE ====
Provide a file:
${script} ./some/path/to/a/file
Pipe from stdin:
echo "hello\nworld!" | ${script}
Redirect from stdin:
${script} < ./some/path/to/a/file
==== USAGE ====
__EOS__
}
handle_lines() {
local input="${1}"
local line_count=0
while read -r line; do
# To satisfy the `set -u` incantation at the top, we have to assign the variable instead of
# a simple ((line_count++))
line_count=$((line_count + 1))
if ((line_count % 2 == 0)); then
printf "%s\n" "$line"
fi
done <"$input"
if ((line_count > 10)); then
printf "big\n"
else
printf "small\n"
fi
}
main() {
# Check if we should read from stdin or a given file
if [[ -t 0 ]]; then
# Input should be a path to a file
set +u
if [[ -z "${1}" ]]; then
usage
die "No input received!"
fi
set -u
local fpath="${1}"
if ! [[ -r "$fpath" ]]; then
die "Unable to read a file at: ${fpath}"
fi
handle_lines "$fpath"
else
# Read from stdin
handle_lines "/dev/stdin"
fi
}
main "${@}"