help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: While loop and stdin


From: Greg Wooledge
Subject: Re: While loop and stdin
Date: Sun, 25 Feb 2024 21:02:08 -0500

On Sun, Feb 25, 2024 at 08:40:42PM -0500, Zachary Santer wrote:
> On Thu, Feb 15, 2024 at 8:41 AM Greg Wooledge <greg@wooledge.org> wrote:
> > If you've got some more subtle purpose in mind, then we need to understand
> > what it is.  In particular, what your script does *not* do is interleave
> > the lines of the input file with the numbers, or read a line at a time
> > from each of two input sources, or reuse the input for each iteration
> > of the numbers, do anything else that the word "doubly" might imply.

> The while loop can read the stdin that was fed to the
> script and then also its own stdin from the printf command. Two stdins, I
> guess.

If there are two input streams to be read, then the question is *how*
you want to use them.  Do you want to read one line from each stream,
alternating back and forth?  If that's the case, then they should both
be opened, using two different file descriptors.  Then you can use two
read commands, one reading from each FD:


#!/bin/bash
# stdin is already open
exec 3< "$file"
while read -r foo && read -r -u3 bar; do
    ...
done
exec 3<&-


That will loop until one of the streams reaches EOF, and then stop.  This
is just *one* possible structure.


> > $ printf "1 2 3\n4 5 6\n" \
> >           | while read a b c; do cat /dev/stdin; echo $a; done
> >
> 
> No clue if his real script would have something within the while loop that
> would read everything 'til EOF or what, but I thought 'cat' was just for
> the purpose of illustration.

This example still confuses me, because it looks like it wants to
close and reopen stdin repeatedly.  Or maybe the intent is "read all
of the available data on stdin at this moment, and whenever it reaches
a state where the next read would block, stop reading there".

Or perhaps the intent is to read all of stdin one time, and reuse that
block of data (stored in memory) on each iteration.

We could write code for each of these cases, but we need to know which
one is desired.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]