help-bash
[Top][All Lists]
Advanced

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

Re: reading from external command


From: Chet Ramey
Subject: Re: reading from external command
Date: Fri, 1 Apr 2022 11:08:55 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Thunderbird/91.7.0

On 3/31/22 7:40 PM, Peng Yu wrote:
I don't get how to modify the while-loop (with unnamed pipes in the
body) to get the exit code in the loop input unnamed pipe. Could you
make it clear by showing a working example? Thanks.

The key is realizing that the process substitution that's redirecting into
the loop is created just before the loop executes, so $! is set to its pid
the first time through the loop. Whether it stays valid for any other loop
iterations depends on the loop body.

So make sure you set the variable you want to hold the desired value of $!
once, the first time through the loop, and use wait on it after the loop
terminates.

while read x y; do
        [ -z "$pid" ] && pid=$!
        echo $x $y      # or other loop body
done < <(echo one two ; exit 42 )

wait $pid
echo $?


--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/



reply via email to

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