读取bash数组(不进入)

Coc*_*ffs 3 linux macos bash while-loop

我正在尝试使用数组while read,但整个数组立即输出.

#!/bin/bash

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

while read -e it ; do
    echo $it
done <<< ${arr[@]}
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*024 10

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

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

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