Sadiel
Sadiel

Reputation: 1384

Create array in bash dynamically

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

Answers (3)

chepner
chepner

Reputation: 530930

The assignment is fine; the lookup is wrong:

echo "${field[$i]}"

Upvotes: 19

Mat
Mat

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

ormaaj
ormaaj

Reputation: 6577

i= field=()
while :; do
    read -r 'field[i++]'
done

Is one way. mapfile is another. Or any of these. However what you've posted is valid.

Upvotes: 2

Related Questions