我可以在bash中读取heredoc的行吗?

Sha*_*off 11 bash heredoc

这就是我正在尝试的.我想要的是最后echo说"一二三四测试......",因为它循环.它不起作用; read line即将到来.这里有一些微妙的东西,或者这不起作用?

array=( one two three )
echo ${array[@]}
#one two three
array=( ${array[@]} four )
echo ${array[@]}
#one two three four


while read line; do
        array=( ${array[@]} $line )
        echo ${array[@]}
done < <( echo <<EOM
test1
test2
test3
test4
EOM
)
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 22

我通常会这样写:

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done <<EOM
test1
test2
test3
test4
EOM
Run Code Online (Sandbox Code Playgroud)

或者,更有可能:

cat <<EOF |
test1
test2
test3
test4
EOF

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done
Run Code Online (Sandbox Code Playgroud)

(请注意,带有管道的版本不一定适用于Bash .Bourne shell将while在当前shell中运行循环,但Bash在子shell中运行它 - 至少在默认情况下是这样.在Bourne shell中,分配在循环后循环将在主shell中可用;在Bash中,它们不是.第一个版本总是设置数组变量,因此它可以在循环之后使用.)

你也可以使用:

array+=( $line )
Run Code Online (Sandbox Code Playgroud)

添加到数组.


sha*_*sha 5

代替

done < <( echo <<EOM
Run Code Online (Sandbox Code Playgroud)

done < <(cat << EOM
Run Code Online (Sandbox Code Playgroud)

为我工作。