Skip to content

Instantly share code, notes, and snippets.

@fionn
Created June 27, 2023 14:38
Show Gist options
  • Save fionn/db0509a2b725bc7868906a09a1757517 to your computer and use it in GitHub Desktop.
Save fionn/db0509a2b725bc7868906a09a1757517 to your computer and use it in GitHub Desktop.
Flexible inputs for Bash scripts
#!/bin/bash
set -euo pipefail
function process {
return 0
}
function main {
mapfile -t inputs < <(echo "${1:-$(</dev/stdin)}")
for input in "${inputs[@]}"; do
process "$input" ||
done
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi

Usage

$ ./stdin.sh $input
$ # or
$ ./stdin.sh <<< $input
$ # or
$ echo $input | ./stdin.sh
$ # or
$ ./stdin.sh  # enter the input(s) and ^D
$ # or
$ ./stdin.sh < inputs.txt
$ # or
$ cat inputs.txt | ./stdin.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment