I have a pretty simple sh
script where I make a system cat
call, collect the results and parse some relevant information before storing the information in an array
, which seems to work just fine. But as soon as I exit the for loop where I store the information, the array
seems to clear itself. I'm wondering if I am accessing the array
incorrectly outside of the for loop. Relevant portion of my script:
#!/bin/sh
declare -a QSPI_ARRAY=()
cat /proc/mtd | while read mtd_instance
do
# split result into individiual words
words=($mtd_instance)
for word in "${words[@]}"
do
# check for uboot
if [[ $word == *"uboot"* ]]
then
mtd_num=${words[0]}
index=${mtd_num//[!0-9]/} # strip everything except the integers
QSPI_ARRAY[$index]="uboot"
echo "QSPI_ARRAY[] at index $index: ${QSPI_ARRAY[$index]}"
elif [[ $word == *"fpga_a"* ]]
then
echo "found it: "$word""
mtd_num=${words[0]}
index=${mtd_num//[!0-9]/} # strip everything except the integers
QSPI_ARRAY[$index]="fpga_a"
echo "QSPI_ARRAY[] at index $index: ${QSPI_ARRAY[$index]}"
# other items are added to the array, all successfully
fi
done
echo "length of array: ${#QSPI_ARRAY[@]}"
echo "----------------------"
done
My output is great until I exit the for loop. While within the for loop, the array
size increments and I can check that the item has been added. After the for loop is complete I check the array
like so:
echo "RESULTING ARRAY:"
echo "length of array: ${#QSPI_ARRAY[@]}"
for qspi in "${QSPI_ARRAY}"
do
echo "qspi instance: $qspi"
done
Here are my results, echo
d to my display:
dev: size erasesize name
length of array: 0
-------------
mtd0: 00100000 00001000 "qspi-fsbl-uboot"
QSPI_ARRAY[] at index 0: uboot
length of array: 1
-------------
mtd1: 00500000 00001000 "qspi-fpga_a"
QSPI_ARRAY[] at index 1: fpga_a
length of array: 2
-------------
RESULTING ARRAY:
length of array: 0
qspi instance:
EDIT: After some debugging, it seems I have two different array
s here somehow. I initialized the array
like so: QSPI_ARRAY=("a" "b" "c" "d" "e" "f" "g")
, and after my for-loop for parsing the array
it is still a, b, c, etc. How do I have two different arrays
of the same name here?