我可以在bash中从Heredoc中读取行吗? [英] Can I read line from a heredoc in bash?

查看:59
本文介绍了我可以在bash中从Heredoc中读取行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我要尝试的.我想要的是最后一个 echo 在循环时说一二三四test1 ...".它不起作用;读取行显示为空.这里有什么微妙的地方吗?还是只是行不通?

Here's what I'm trying. What I want is the last echo to say "one two three four test1..." as it loops. It's not working; read line is coming up empty. Is there something subtle here or is this just not going to work?

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
)

推荐答案

我通常会这样写:

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

或者,甚至更有可能:

cat <<EOF |
test1
test2
test3
test4
EOF

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done

(请注意,带有管道的版本不一定适合Bash.Bourneshell将在当前shell中运行 while 循环,但是Bash在子shell中运行-至少通过默认值.在Bourne Shell中,在循环之后在主外壳中可以使用在循环中进行的分配;在Bash中则不能使用.第一个版本始终设置数组变量,因此可以在循环后使用.)

(Note that the version with a pipe will not necessarily be suitable in Bash. The Bourne shell would run the while loop in the current shell, but Bash runs it in a subshell — at least by default. In the Bourne shell, the assignments made in the loop would be available in the main shell after the loop; in Bash, they are not. The first version always sets the array variable so it is available for use after the loop.)

您还可以使用:

array+=( $line )

添加到数组中.

这篇关于我可以在bash中从Heredoc中读取行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆