bash 在bash中动态创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13276788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:55:29  来源:igfitidea点击:

Create array in bash dynamically

bash

提问by Sadiel

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

采纳答案by chepner

The assignment is fine; the lookup is wrong:

任务很好;查找错误:

echo "${field[$i]}"

回答by Mat

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, ^Din the keyboard), then prints the number of elements read and the whole array.

当没有更多输入可用时(文件末尾,^D在键盘中),它停止读取,然后打印读取的元素数和整个数组。

回答by ormaaj

i= field=()
while :; do
    read -r 'field[i++]'
done

Is one way. mapfileis another. Or any of these. However what you've posted is valid.

是一种方式。mapfile是另一个。或任何这些。但是,您发布的内容是有效的。