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?
EOFin 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 (likeecho) inside a here-document, just the text you want to pass.