I needed to write a script to enter multi-line input to a program (psql
).
After a bit of googling, I found the following syntax works:
c
Long story short, EOF
marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline.
A lot of confusion comes from how cat
actually works it seems.
You can use cat
with >>
or >
as follows:
$ cat >> temp.txt
line 1
line 2
While cat
can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin
but typing in a separate text editor. This is what Wikipedia article means by:
it is a section of a source code file that is treated as if it were a separate file.
A little extension to the above answers. The trailing >
directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >>
that appends, adding your new content to the end of the file, as in:
cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert /var/sharedFolder/sometin/vsdc/cert nfs
EOF
This extends your fstab
without you having to worry about accidentally modifying any of its contents.
In your case, "EOF" is known as a "Here Tag". Basically <<Here
tells the shell that you are going to enter a multiline string until the "tag" Here
. You can name this tag as you want, it's often EOF
or STOP
.
Some rules about the Here tags:
example:
$ cat >> test <<HERE
> Hello world HERE <-- Not by itself on a separate line -> not considered end of string
> This is a test
> HERE <-- Leading space, so not considered end of string
> and a new line
> HERE <-- Now we have the end of the string