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: Wed, 14 Feb 2024 16:33:43 -0500

On Wed, Feb 14, 2024 at 08:00:41PM +0100, Mohammad Akhlaghi wrote:
> However, if a command within the while loop reads from standard input, the
> while loop doesn't read that line any more:
> 
> $ printf "1 2 3\n4 5 6\n" \
>          | while read a b c; do cat /dev/stdin; echo $a; done
> 4 5 6
> 1

Yeah, you can't use stdin for two different purposes at the same time
like this.  Use a different file descriptor for the outer loop.  If
the input is *really* coming from a file, then it's simple:


while read 0<&3 -r a b c; do
    cat /dev/stdin
    echo "$a"
done 3< my-input-file


If the input is actually being piped in, as in your example, then you
can use a process substitution:


while read 0<&3 -r a b c; do
    cat /dev/stdin
    echo "$a"
done 3< <(printf ...)


See also <https://mywiki.wooledge.org/BashFAQ/089>.



reply via email to

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