Tugger the SLUGger!SLUG Mailing List Archives

Re: [SLUG] shell scripting help


On Fri, Sep 18, 2009 at 11:42 PM, Daniel Bush <dlb.id.au@xxxxxxxxx> wrote:
> Hi,
> Writing a little utility to help me on something but having trouble.
> Why does f stay blank?
>
> danb@lin4:test$ echo "foo|bar" | awk 'BEGIN{RS="|"}{ print $1 }' | while
> read s; do echo $s; f=$s; done; echo "'$f'"
> foo
> bar
> ''

As I understand it (only just looked this up), it's to do with the
fact that you're subshelling[1] by piping output to the while loop,
which makes the $f variable only visible in the subshell and not the
parent process. After the while loop ends, it returns control to the
parent process where the $f variable can't be seen. This works:

while read s; do
        echo $s;
        f=$s;
done < <(echo "foo|bar" | awk 'BEGIN{RS="|"}{ print $1 }')

echo "'$f'"

HTH,
- Gonzalo

[1] http://fvue.nl/wiki/Bash:_Piped_`while-read'_loop_starts_subshell