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
To initialise array with elements in Bash, use assignment operator = , and enclose all the elements inside braces () separated by spaces in between them. We may also specify the index for each element in the array.
sh does not support array, and your code does not create an array. It created three variable arr1 , arr2 , arr3 . To initialize an array element in a ksh -like shell, you must use syntax array[index]=value . To get all element in array, use ${array[*]} or ${array[@]} .
Access Array Elements Similar to other programming languages, Bash array elements can be accessed using index number starts from 0 then 1,2,3…n. This will work with the associative array which index numbers are numeric. To print all elements of an Array using @ or * instead of the specific index number.
The assignment is fine; the lookup is wrong:
echo "${field[$i]}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With