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

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

Can I read line from a heredoc in bash?

bashheredoc

提问by Shawn J. Goff

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

这就是我正在尝试的。我想要的是最后一个echo说“一二三四测试1 ...”,因为它循环。它不起作用;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
)

回答by Jonathan Leffler

I would normally write:

我通常会写:

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

Or, even more likely:

或者,更有可能:

cat <<EOF |
test1
test2
test3
test4
EOF

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

(Note that the version with a pipe will not necessarily be suitable in Bash. The Bourne shell would run the whileloop 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.)

(请注意,带有管道的版本不一定适合 Bash。Bourne shell 会while在当前 shell 中运行循环,但 Bash 在子 shell 中运行它——至少在默认情况下。在 Bourne shell 中,在循环将在循环后的主 shell 中可用;在 Bash 中,它们不是。第一个版本始终设置数组变量,以便在循环后可用。)

You could also use:

您还可以使用:

array+=( $line )

to add to the array.

添加到数组中。

回答by sha

replace

代替

done < <( echo <<EOM

with

done < <(cat << EOM

Worked for me.

对我来说有效。

回答by hlovdal

You can put the command in front of while instead:

您可以将命令放在 while 前面:

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