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

查看:27
本文介绍了为什么 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天全站免登陆