Bash scripting "while" problem

Giles Orr gilesorr-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org
Fri Jun 7 01:51:34 UTC 2013


On 6 June 2013 17:05, Chris F.A. Johnson <chris-E7bvbYbpR6jSUeElwK9/Pw at public.gmane.org> wrote:
> On Wed, 5 Jun 2013, Giles Orr wrote:
>
>> The code below appears to work, in that the debug echo command in the
>> middle of the while loop kicks out the responses I want.  But outside
>> the while loop the ip[] array is empty.  I've run into this before,
>> never really figured out why.  My wild guess without much
>> comprehension is that the while (and thus the array) is in a subshell
>> because of the pipe so the variable is never set in the script proper
>> ...
>>
>> So am I correct?  And how would I fix it?  Thanks.
>>
>> index=0
>> ifconfig | grep "inet addr:" | awk '{ print $2 }' |
>> while read line
>> do
>>    tmp="${line}"
>>    tmp2="${tmp#addr:}"
>>    ip[${index}]="${tmp2%.?}"
>>    echo "ip[] is ${ip[${index}]}"
>>    index=$(($index+1))
>> done
>> echo "outside while, first ip is ${ip[0]}"
>
>
>   With bash-4.2, you can have the last element of a pipeline executed
>   in the current shell (the way ksh does it):
>
> shopt -s lastpipe
>
>   Or, you can brace everything after the last pipe:
>
> cmd1 | cmd2 | {
> while read line
> do
>  x=whatever
> done
> echo "x=$x"
> }
>
>    Or you can do it without using external commands beyond ifconfig:
>
> temp=$(ifconfig $if)
> temp=${temp#*addr:}
> ip=${temp%% *}

I used "shopt -s lastpipe" and that fixed it immediately.  Thank you so much.

--
Giles
http://www.gilesorr.com/
gilesorr-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list