20

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
5
  • What is your actual problem? Aside from some minor issues, your code is fine. Commented Nov 7, 2012 at 19:38
  • It works like a simple variable. If I the input is test, it echo: {test[0]} Commented Nov 7, 2012 at 19:44
  • I don't see any echo there. You just have an infinite loop that appends an array and does nothing with it. Yes expanding "$test" is always equivalent to "${test[0]}" (even if test isn't an array). Commented Nov 7, 2012 at 19:51
  • I edited the post. I added echo {$field[$i]} Commented Nov 7, 2012 at 19:53
  • 1
    I saw the error is the $ symbol after the bracket Commented Nov 7, 2012 at 19:54

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

Comments

19

The assignment is fine; the lookup is wrong:

echo "${field[$i]}"

Comments

2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.