Reputation: 1384
I would like to create and fill an array dynamically but it doesn't work like this:
i=0
while true; do
read input
field[$i]=$input
((i++))
echo {$field[$i]}
done
Upvotes: 20
Views: 44675
Reputation: 530930
The assignment is fine; the lookup is wrong:
echo "${field[$i]}"
Upvotes: 19
Reputation: 206679
Try something like this:
#! /bin/bash
field=()
while read -r input ; do
field+=("$input")
done
echo Num items: ${#field[@]}
echo Data: ${field[@]}
It stops reading when no more input is available (end of file, ^D
in the keyboard), then prints the number of elements read and the whole array.
Upvotes: 20