我可以从 bash 中的定界文档中读取行吗?

发布于 2024-08-22 23:56:20 字数 406 浏览 7 评论 0原文

这就是我正在尝试的。我想要的是最后一个 echo 在循环时说“一二三四 test1...”。它不起作用; 读取行变为空。这里有什么微妙的地方吗?或者这根本行不通?

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
)

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
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

赢得她心 2024-08-29 23:56:20

我通常会写:

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。Bourne shell 会在当前 shell 中运行 while 循环,但 Bash 运行它在子 shell 中 - 至少在 Bourne shell 中,循环中进行的赋值在循环之后在主 shell 中可用;在 Bash 中,它们总是设置数组变量,所以它是。可在循环后使用。)

您还可以使用:

array+=( $line )

添加到数组中。

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 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.)

You could also use:

array+=( $line )

to add to the array.

完美的未来在梦里 2024-08-29 23:56:20

替换

done < <( echo <<EOM

done < <(cat << EOM

“为我工作”。

replace

done < <( echo <<EOM

with

done < <(cat << EOM

Worked for me.

老街孤人 2024-08-29 23:56:20

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

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

You can put the command in front of while instead:

(echo <<EOM
test1
test2
test3
test4
EOM
) | while read line; do
        array=( ${array[@]} $line )
        echo ${array[@]}
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文