[buug] loops and pipe sinks are subshells, aaaargh

Tony Godshall togo at of.net
Fri Aug 5 11:47:12 PDT 2011


[IZ]
>> Sigh.  When I wrote my post I assumed the problem I described would be
>> instantly recognized by any Unix veteran who (I kept assuming)  ...

Ian:

Well, color us whooshed.  By the way, you'll get better answers
faster if you provide complete working code in your questions.
It's not always about skill: it can also be about time.

[MP]
> Yes, instantly recognized.  I believe it's also well covered in shell
> FAQ(s) ...
...
> Among possible approaches:
>
> #!/bin/sh
> output_foo(){
> echo 'foo 1 ...

Michael:

Well, you still don't get the variable to the outside of the subshell,
the point of the original question.

This does:

start script

#!/bin/bash
# note I changed Michael's shebang because of the bashisms)

output_foo(){
echo 'foo 1
bar 23
baz 4
foo 53
foobar 6'
}

total=$(
  output_foo | (
    total=0
    while read item count
    do
      let total=total+count
    done
    echo $total
  )
)

echo $total

end script

end message



More information about the buug mailing list