Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

scripting - Why is bash only appending first element to array

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...