Bash scripting "while" problem

Chris F.A. Johnson chris-E7bvbYbpR6jSUeElwK9/Pw at public.gmane.org
Thu Jun 6 21:05:08 UTC 2013


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%% *}

-- 
    Chris F.A. Johnson, <http://cfajohnson.com/>
    Author:
    Pro Bash Programming: Scripting the GNU/Linux Shell (2009, Apress)
    Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
--
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