help-bash
[Top][All Lists]
Advanced

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

Re: Check the error status of process substitution


From: Masahiro Yamada
Subject: Re: Check the error status of process substitution
Date: Tue, 7 Jun 2022 05:19:48 +0900

On Tue, Jun 7, 2022 at 4:05 AM Kerin Millar <kfm@plushkava.net> wrote:
>
> On Tue, 7 Jun 2022 03:25:49 +0900
> Masahiro Yamada <masahiroy@kernel.org> wrote:
>
> > My main motivation for using a process substitution is
> > to reflect variable changes made in the loop
> > (like 'nr_lines' in the sample code)
> > to the outside of the loop.
> >
> > A pipe does not work that way
> > since the loop is executed in a subshell.
>
> Bash >=4.2 supports lastpipe so that could be an option for you. It requires 
> that job control be disabled but this is already the case for non-interactive 
> instances. I refer you to the example beneath.
>
> #!/bin/bash
> shopt -s lastpipe
> { echo line1; false; } | while read -r; do
>         captured_line=$REPLY
> done
> status=${PIPESTATUS[0]}
> declare -p status captured_line
>
> --
> Kerin Millar


Perfect!

I used pipefail to bail out
if the first command in the pipeline fails.

I rewrote the code as follows, and
this achieved what I wanted to do.


-------------(sample code modified)--------------
#!/bin/bash

set -e
set -o pipefail
shopt -s lastpipe

nr_lines=0

{ echo a; echo b; echo c; } |
while read -r _; do
        nr_lines=$(( nr_lines + 1 ))
done

echo $nr_lines
-------------(sample code modified end)--------------


I learned new things today.

Thank you.

-- 
Best Regards
Masahiro Yamada



reply via email to

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