我可以从 bash 中的定界文档中读取行吗?
这就是我正在尝试的。我想要的是最后一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常会写:
或者,更有可能是:
(请注意,带有管道的版本不一定适合 Bash。Bourne shell 会在当前 shell 中运行
while
循环,但 Bash 运行它在子 shell 中 - 至少在 Bourne shell 中,循环中进行的赋值在循环之后在主 shell 中可用;在 Bash 中,它们总是设置数组变量,所以它是。可在循环后使用。)您还可以使用:
添加到数组中。
I would normally write:
Or, even more likely:
(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:
to add to the array.
替换
为
“为我工作”。
replace
with
Worked for me.
您可以将命令放在 while 前面:
You can put the command in front of while instead: