我如何在while循环中向文件输出多行?

问题描述 投票:0回答:2

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

我正在尝试每2秒将“ Hello World”输出到hello.txt,并能够每2秒查看一次hello.txt更新。我可以通过运行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”?

bash heredoc
2个回答
0
投票

您可以重定向子shell的输出

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

0
投票

您可以使用cat代替echo。

while true
do
    cat << EOL >> hello.txt
Hello
World
EOL
    sleep 2                                                                     
done
© www.soinside.com 2019 - 2024. All rights reserved.