How to use a here documents to write data to a file in bash script

A “here document” is a way to specify multiple lines of text as the input to a command in a shell script. In a bash script, you can use a here document to write data to a file. Here’s an example of how to use a here document to write data to a file:

 
#!/bin/bash

# The file to write to
file="test.txt"

# The data to write to the file
cat << EOF > "$file"
This is a line of text.
This is another line of text.
And this is yet another line.
EOF

In this example, the cat command writes the lines of text contained within the here document to the file specified by "$file". The > "$file" operator is used to redirect the output of cat to the file. The marker EOF is used to indicate the end of the here document. Note that you can use any string as the marker, but it should not appear anywhere within the text of the here document.

Leave a Comment