
Mailing List Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[tlug] Bash looping issue
- Date: Tue, 12 Oct 2010 10:14:06 -0500
- From: "Daniel A. Ramaley" <daniel.ramaley@example.com>
- Subject: [tlug] Bash looping issue
- Organization: Drake University
Hello. 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
# Testing done with: GNU bash, version 4.1.5(1)-release
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[@example.com" | sort -z | while read -d $'\0' key ; do
#for key in "${!ORIG[@example.com" ; 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[@example.com:\t${COPY[@example.com" ; # Shows changes
done
echo -e "\nORIG\n----"
for key in "${!ORIG[@example.com" ; do # Prints the ORIG array.
echo -e "$key\t${ORIG[$key]}"
done
echo -e "\nCOPY\n----"
for key in "${!COPY[@example.com" ; 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@example.com
Home |
Main Index |
Thread Index