【问题标题】:How do I output multiple lines to a file within a while loop?如何在while循环中将多行输出到文件?
【发布时间】:2020-02-10 16:13:03
【问题描述】:

我正在编写一个 Bash 脚本,我正在尝试打印出多行输出并将它们打印到一个文件中。这是我到目前为止所尝试的,这只是一个示例,但与我想要完成的非常相似。

我正在尝试每 2 秒将“Hello World”打印到 hello.txt,并且能够看到 hello.txt 每 2 秒更新一次。我会通过运行 tail -f hello.txt 来做到这一点。这是我到目前为止所尝试的。

echo "Hello" >> hello.txt
echo "World" >> hello.txt

但我需要在循环中的每一行之后运行“>> hello.txt”。所以我学会了运行以下命令将文本块输出到文件

cat >> hello.txt << EOL
echo "Hello"
echo "World"
EOL

然后我应用了 while 循环。

while true
do
    echo >> hello.txt << EOL
    echo "Hello"
    echo "World"
    EOL
    sleep 2
done

然后我得到了以下错误。

./test.sh: line 10: warning: here-document at line 7 delimited by end-of-file (wanted `EOL')
./test.sh: line 11: syntax error: unexpected end of file

然后我尝试将文件输出放在 while 循环之外

echo >> hello.txt << EOL
while true
do
    echo "Hello"
    echo "World"
    sleep 2
done
EOL

但这打印出了实际的代码,而不是它的意图。如何在循环中将多行打印到文本文件,而不必在每行之后写“>> hello.txt”?

【问题讨论】:

  • 您不能缩进 here-document 或其结尾分隔符(脚本中的EOF),除非您使用“-”(如&lt;&lt;-EOF),在这种情况下您可以使用制表符缩进(但不能使用空格)。此外,您不要在 here-document 中使用 shell 命令(如 echo),而只是要传递的文本。

标签: bash heredoc


【解决方案1】:

您可以重定向子shell的输出

while true
do
    (
    echo "Hello"
    echo "World"
    ) >> hello.txt
    sleep 2
done

【讨论】:

    【解决方案2】:

    你可以用 cat 代替 echo。

    while true
    do
        cat << EOL >> hello.txt
    Hello
    World
    EOL
        sleep 2                                                                     
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2020-10-25
      • 2012-01-02
      • 2019-02-17
      • 1970-01-01
      • 2011-09-19
      相关资源
      最近更新 更多