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

www.la‮u‬tturi.com
How to use a here documents to write data to a file in bash script

A here document (or here-document) is a way to specify multi-line input for a command in a shell script. It allows you to embed a block of text in a script, which will be interpreted as standard input for the command.

To use a here document to write data to a file in a bash script, you can use the cat command and redirect the output to the desired file. For example:

cat <<EOF > /path/to/file.txt
This is the first line of the file.
This is the second line of the file.
EOF

This will create a new file at /path/to/file.txt, or overwrite the file if it already exists, and write the specified text to the file. The text is delimited by the EOF marker, which marks the beginning and end of the here document.

You can use other commands in place of cat, such as echo or printf, to write the data to the file. For example:

echo "This is the first line of the file." > /path/to/file.txt
echo "This is the second line of the file." >> /path/to/file.txt

This will write the two lines of text to the file, with the > operator overwriting the file and the >> operator appending to the end of the file.

You can also use variables in the here document by enclosing them in $ signs, like this:

cat <<EOF > /path/to/file.txt
This is the first line of the file.
This is the second line of the file.
The value of the variable is $my_variable.
EOF

This will write the value of the variable $my_variable to the file, along with the other lines of text.

Created Time:2017-10-29 22:08:40  Author:lautturi