7

I'm trying to read a list of files from stdin, with each file delimited by a newline, however I'm noticing that only the first element is getting appended to the list. I noticed this by simply entering two strings and then q. Can anyone explain why?

files=()
read input

while [ "$input" != "q" ] ; 
do
    files+=( "$input" )
    read input
done

for f  in $files ; 
do
    echo "the list of files is:"
    echo "$f"
    echo "The length of files is ${#files} " #prints 1, even if 2+ are entered
done

1 Answers1

9

Actually your files+=( "$input" ) expression is adding elements to your array but you are not iterating it correctly.

Your last loop should be:

for f in "${files[@]}"; do
    echo "element is: $f"
done

Test (thanks to @fedorqui)

$ a+=(1)
$ a+=("hello")
$ a+=(3)
$ for i in "${a[@]}"; do echo "$i"; done
1
hello
3
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Fast! I added some explanation, feel free to add it to your answer if you find it useful :) – fedorqui Nov 04 '14 at 16:26
  • 1
    Thanks I have added most of it to my answer to make it more clear. – anubhava Nov 04 '14 at 16:29
  • Thanks, I suppose that `$files` refers to the head of the array? –  Nov 04 '14 at 16:30
  • Yes that is true, `$files` gets you first element from array. – anubhava Nov 04 '14 at 16:32
  • 1
    Yes, `$var` is equivalent to `${var[0]}`. – fedorqui Nov 04 '14 at 16:48
  • Why is $var the same as ${var[0]} in this case, but not when I assign a variable to the output of something that gives multiple-line output? I'm able to echo $var in that case and see all of the elements. – Bennett Mar 19 '15 at 17:15
  • @Bennett: [See this answer for more details](http://stackoverflow.com/questions/8880603/loop-through-array-of-strings-in-bash-script/8880633#8880633) – anubhava Mar 19 '15 at 17:32