[Cialug] Bash looping issue

Ken MacLeod ken at bitsko.slc.ut.us
Wed Oct 13 11:18:03 CDT 2010


On Tue, Oct 12, 2010 at 10:07 AM, Daniel A. Ramaley
<daniel.ramaley at drake.edu> wrote:
> In the example script below, i define an associative array and then make
> a copy of it using a loop to copy each key/value pair. It seems to work
> quite nicely... within the loop. Once outside the loop, the copied array
> loses its data. The bizarre thing is that if i switch the loop construct
> from a "while" to a "for", it works.

> # Comment out the "printf...while" loop and comment in the "for" loop
> # and it magically starts working. I don't know why.
> printf "%s\000" "${!ORIG[@]}" | sort -z | while read -d $'\0' key ; do
> #for key in "${!ORIG[@]}" ; do

My first thought is that the "while" is running in a pipeline so it's
running in a subprocess rather than the current process, so any
variables inside the loop are local to the subprocess.  However, I
thought I've done that before too and it worked right...

You might try:

    while read -d $'\0' key <(printf "%s\000" "${!ORIG[@]}" | sort -z); do

so the printf | sort runs in a background process and the while stays
in the current process.  I've never tried that before but it popped up
when I went looking for the other kinds of "fancy" pipe handling that
I know bash has ;-)

  -- Ken


More information about the Cialug mailing list