0

I'm writing a Bash script and I'm trying to print out multiple lines of output and print them to a file. Here's what I've tried so far, this is just an example, but very similar to what I'm trying to accomplish.

I'm trying to print out "Hello World" to hello.txt every 2 seconds and be able to see hello.txt updated every 2 seconds. I would do this by running tail -f hello.txt. Here's what I've tried so far.

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

But I would need to run " >> hello.txt " after each line in my loop. So I learned to run the following to output a block of text to a file

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

Then I applied the while loop.

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

But then I got the following error.

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

Then I tried putting the file-output outside the while loop

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

But this printed out the actual code and not what it was intended to do. How can I print out multiple lines in a loop to a text file without having to write " >> hello.txt " after every line?

1
  • 1
    You can't indent the here-document or its end delimiter (EOF in your script), unless you use "-" (as in <<-EOF), in which case you can indent with tabs (but not spaces). Also, you don't use shell commands inside (like echo) inside a here-document, just the text you want to pass. Commented Oct 14, 2019 at 4:12

2 Answers 2

1

You can redirect the output of a subshell

while true
do
    (
    echo "Hello"
    echo "World"
    ) >> hello.txt
    sleep 2
done
Sign up to request clarification or add additional context in comments.

Comments

0

You can use cat instead of echo.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.