读取 bash 数组时(未读入)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37503981/
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-18 14:42:07  来源:igfitidea点击:

while read bash array (not into)

linuxbashmacoswhile-loop

提问by Cocoa Puffs

I'm trying to use an array with while read, but the entire array is output at once.

我正在尝试将数组与 一起使用while read,但会立即输出整个数组。

#!/bin/bash

declare -a arr=('1:one' '2:two' '3:three');

while read -e it ; do
    echo $it
done <<< ${arr[@]}

It should output each value separately (but doesn't), so maybe while read isn't the hot ticket here?

它应该单独输出每个值(但不是),所以也许读取时不是这里的热门单?

回答by John1024

For this case, it is easier to use a forloop:

对于这种情况,使用for循环更容易:

$ declare -a arr=('1:one' '2:two' '3:three')
$ for it in "${arr[@]}"; do echo $it; done
1:one
2:two
3:three

The while readapproach is very useful (a) When you want to read data from a file, and (b) when you want to read in a nul or newline separated string. In your case, however, you already have the data in a bashvariable and the forloop is simpler.

while read方法非常有用(a)当您想从文件中读取数据时,以及(b)当您想读取空或换行符分隔的字符串时。但是,在您的情况下,您已经将数据保存在bash变量中,并且for循环更简单。

回答by sumitya

possible by while loop

可能通过 while 循环

#!/bin/bash

declare -a arr=('1:one' '2:two' '3:three');
len=${#arr[@]}
i=0
while [ $i -lt $len ]; do
    echo "${arr[$i]}"
    let i++
done