[Cialug] Bash looping issue

Daniel A. Ramaley daniel.ramaley at drake.edu
Tue Oct 12 10:07:15 CDT 2010


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. I'd really like to use the "while" 
loop, however, so that in more complicated scripts i can process the 
keys in sorted order. (This would be useful, for example, in building a 
sorted list of the keys of an associative array.) I've pasted my sample 
script and the output below. Any ideas?




#!/bin/bash
declare -A ORIG
ORIG=(['key 1']='A'
      ['key 2']='B'
      ['key 3']='C')

declare -A COPY
# 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
    COPY["${key}"]="${ORIG[$key]}"
    #COPY+=(["${key}"]="${ORIG[$key]}") # Alternate form of assignment
    echo -e "DEBUG:\tProcessing key=\"${key}\", val=\"${ORIG[$key]}\""
    echo -e "DEBUG:\t${!COPY[@]}\nDEBUG:\t${COPY[@]}" ; # Shows changes
done

echo -e "\nORIG\n----"
for key in "${!ORIG[@]}" ; do     # Prints the ORIG array.
    echo -e "$key\t${ORIG[$key]}"
done
echo -e "\nCOPY\n----"
for key in "${!COPY[@]}" ; do     # Prints COPY only if it was created
    echo -e "$key\t${COPY[$key]}" # with "for" loop--prints nothing if
done                              # created with "while".




OUTPUT USING WHILE LOOP
=======================

DEBUG:	Processing key="key 1", val="A"
DEBUG:	key 1
DEBUG:	A
DEBUG:	Processing key="key 2", val="B"
DEBUG:	key 1 key 2
DEBUG:	A B
DEBUG:	Processing key="key 3", val="C"
DEBUG:	key 1 key 3 key 2
DEBUG:	A C B

ORIG
----
key 1	A
key 3	C
key 2	B

COPY
----


OUTPUT USING FOR LOOP
=====================

DEBUG:	Processing key="key 1", val="A"
DEBUG:	key 1
DEBUG:	A
DEBUG:	Processing key="key 3", val="C"
DEBUG:	key 1 key 3
DEBUG:	A C
DEBUG:	Processing key="key 2", val="B"
DEBUG:	key 1 key 3 key 2
DEBUG:	A C B

ORIG
----
key 1	A
key 3	C
key 2	B

COPY
----
key 1	A
key 3	C
key 2	B





__
Daniel A. Ramaley
Network Engineer 2

Dial Center 118, Drake University
2407 Carpenter Ave / Des Moines IA 50311 USA
Tel: +1 515 271-4540
Fax: +1 515 271-1938
E-mail: daniel.ramaley at drake.edu


More information about the Cialug mailing list