help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] populating an array with piped output in a loop


From: Chet Ramey
Subject: Re: [Help-bash] populating an array with piped output in a loop
Date: Tue, 29 Nov 2011 09:42:07 -0500

> Hi All,
> 
> I understand the reason the following snippet of code will not work
> because the pipe invokes a sub-shell.
> 
>       COUNTER=0
>       DISKS=()
>       DISKS_NAME=()
>       grep "^disk[0-9]*=" /etc/diskinfo |
>       while read LINE;
>       do
>               DISKS[${COUNTER}]=`echo ${LINE}|sed -e "s/.*=//"`
>               DISKS_NAME[${COUNTER}]=`echo ${LINE}|sed -e "s/=.*//"`
>               COUNTER=$((${COUNTER} + 1))
>       done
> 
> What is the best way to populate an array with the contents of a file
> when you need to transform each line read from the file?

You can use process substitution and input redirection into the while
loop, or play around with bash-4.2 and the `lastpipe' shell option that
causes the last process in a pipeline to be run in the parent shell
context (as long as job control is not active).

Chet

-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU    address@hidden    http://cnswww.cns.cwru.edu/~chet/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]