Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array in bash dynamically

Tags:

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
like image 530
Sadiel Avatar asked Nov 07 '12 19:11

Sadiel


People also ask

How do I initialize an array in bash?

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.

How do you create an array in SH?

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[@]} .

How do you access an array in bash?

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.


Video Answer


2 Answers

The assignment is fine; the lookup is wrong:

echo "${field[$i]}"
like image 189
chepner Avatar answered Oct 11 '22 08:10

chepner


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.

like image 40
Mat Avatar answered Oct 11 '22 10:10

Mat