LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   how to load an array from a file in RHEL bash script (http://www.linuxquestions.org/questions/linux-general-1/how-to-load-an-array-from-a-file-in-rhel-bash-script-674018/)

steven.c.banks 10-03-2008 02:57 PM

how to load an array from a file in RHEL bash script
 
I want to load an array from a file. I developed the following:

declare -a targetarray
count=0

while read line
do
targetarray[$count]=$line
((count++))
done < /tmp/find-fmfm-reachlist-sorted.txt

When I echo $line, it shows each line in the file, as expected. An echo of $count shows it increasing. However, an echo of $targetarray[$count] shows it storing the first value of $line in each row in the array. What am I doing wrong?

line = 2143347423 9038945094 130
targetarray = 2143347423 9038945094 130[0]
line = 2147292028 9034514086 130
targetarray = 2143347423 9038945094 130[1]
line = 2148080083 9034514086 130
targetarray = 2143347423 9038945094 130[2]
.
.
.

colucix 10-03-2008 04:08 PM

It should work! How did you echo the array elements? Which command?

steven.c.banks 10-03-2008 04:18 PM

Thanks! I added the echo commands back into the script, and an if statement to stop it:

while read line
do
echo "count = $count"
echo "line = $line"
targetarray[$count]=$line
echo "targetarray row = $targetarray[$count]"
((count++))
if [ $count -gt 5 ]
then
exit
fi
done < /tmp/find-fmfm-reachlist-sorted.txt

output:
count = 0
line = 2143347423 9038945094 130
targetarray row = 2143347423 9038945094 130[0]
count = 1
line = 2147292028 9034514086 130
targetarray row = 2143347423 9038945094 130[1]
count = 2
line = 2148080083 9034514086 130
targetarray row = 2143347423 9038945094 130[2]
count = 3
line = 2149126551 9034515033 130
targetarray row = 2143347423 9038945094 130[3]
count = 4
line = 2392184778 2394951912 130
targetarray row = 2143347423 9038945094 130[4]
count = 5
line = 2392184779 2394951912 130
targetarray row = 2143347423 9038945094 130[5]

colucix 10-03-2008 04:24 PM

You forgot the curly brackets:
Code:

echo "targetarray row = ${targetarray[$count]}"
:)


All times are GMT -5. The time now is 07:14 PM.