I propose a function that synthesizes the previous very interesting answers:
File test.sh:
#!/bin/bash
function init_STDIN() {
## Version 1.0.0
## Creates the global variable array indexed STDIN
## which contains the possible lines sent in the
## file descriptor /dev/stdin of the script
declare -ga STDIN
read -t0 || return 1
while read LINE; do
STDIN[${#STDIN[@]}]="$LINE"
done < <(cat -)
test ${#STDIN[@]} -ne 0
}
if init_STDIN; then
echo "Feed provided on /dev/stdin. Processing..."
echo "For this example, /dev/stdin is:"
for ((I=0; I<${#STDIN[@]}; I++)); do
echo ${STDIN[$I]}
done
else
echo "Working without any feed on /dev/stdin..."
fi
echo
echo "For this example, the ${#@} parameter(s) provided on the command line is(are) :"
echo $@
TESTS:
$ ./test.sh some args ...
Working without any feed on /dev/stdin...
For this example, the 3 parameter(s) provided on the command line is(are) :
some args ...
$ seq 1 10 | sed 's/ /\n/g' | ./test.sh some args ...
Feed provided on /dev/stdin. Processing...
For this example, /dev/stdin is:
1
2
3
4
5
6
7
8
9
10
For this example, the 3 parameter(s) provided on the command line is(are) :
some args ...
$ seq 1 10 | sed 's/ /\n/g' | (exec 0<&-; ./test.sh some args ...)
Working without any feed on /dev/stdin...
For this example, the 3 parameter(s) provided on the command line is(are) :
some args ...
read
with a timeout... – Kusalananda Nov 28 '18 at 12:14stdin
has been closed for some other reason, it will wrongly deduce that it reads from a file given onstdin
. But, I do not see how to do better than that... If you can come with a better solution, I would be delighted to see it! – perror Nov 28 '18 at 12:30read
would return (with a "bad filediscriptor" error) immediately, and that could be handled as a data error, i.e. the data was supposed to come from standard input, but there was something wrong with it. – Kusalananda Nov 28 '18 at 12:45test ! -t 0
case. It works more reliably that way. – HappyFace Sep 20 '20 at 18:55