为什么bash仅将第一个元素附加到数组 [英] Why is bash only appending first element to array

查看:88
本文介绍了为什么bash仅将第一个元素附加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从stdin中读取文件列表,每个文件都由换行符分隔,但是我注意到只有第一个元素被追加到列表中.我通过简单地输入两个字符串然后输入q注意到了这一点.谁能解释为什么?

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

推荐答案

实际上,您的files+=( "$input" )表达式正在向数组中添加元素,但是您没有正确地对其进行迭代.

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

测试(感谢@fedorqui)

$ a+=(1)
$ a+=("hello")
$ a+=(3)
$ for i in "${a[@]}"; do echo "$i"; done
1
hello
3

这篇关于为什么bash仅将第一个元素附加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆