Tugger the SLUGger!SLUG Mailing List Archives

Re: [SLUG] shell scripting help


2009/9/19 Rodolfo Martínez <rmtzcx@xxxxxxxxx>:
> Yes, but the last instruction is doing "f=$s"

Right, but f should be set to 'bar' since it won't go into the while
loop after the 2nd read (as it's a non true value). Well, it won't be
set to 'bar' in the OP's script because of the subshell.

> About the sub-shelling stuff... in this case that is not why 'f' is blank
>
> The 'while' is executed in the same shell
>
> [martir@amartir01 ~]$ echo $$ ; echo -n "foo|bar" | awk
> 'BEGIN{RS="|"}{ print $1 }' | while read s; do f=$s ; echo "f=$f" ;
> echo $$ ; done ; echo "f=$f"
> 5997  <== Same shell
> f=foo
> 5997  <== Same shell
> f=bar
> 5997  <== Same shell
> f=

I believe $$ gives the pid of the parent pid. Quoting:

"Within a script, inside a subshell, $$ returns the PID of the script,
not the subshell."

You could replace $$ with $BASH_SUBSHELL (boolean indicating if you're
in a subshell). Output:

$ echo $BASH_SUBSHELL ; echo -n "foo|bar" | awk 'BEGIN{RS="|"}{ print
$1 }' | while read s; do f=$s ; echo "f=$f"; echo $BASH_SUBSHELL;
done; echo "f=$f"
0
f=foo
1
f=bar
1
f=

- Gonzalo