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:
cat << EOF | psql ---params
BEGIN;
`pg_dump ----something`
update table .... statement ...;
END;
EOF
This correctly constructs the multi-line string (from BEGIN;
to END;
, inclusive) and pipes it as an input to psql
.
But I have no idea how/why it works, can some one please explain?
I'm referring mainly to cat << EOF
, I know >
outputs to a file, >>
appends to a file, <
reads input from file.
What does <<
exactly do?
And is there a man page for it?
This isn't necessarily an answer to the original question, but a sharing of some results from my own testing. This:
will produce the same file as:
So, I don't see the point of using the cat command.
Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:
or even without the new line
This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.
From
man bash
:Using tee instead of cat
Not exactly as an answer to the original question, but I wanted to share this anyway: I had the need to create a config file in a directory that required root rights.
The following does not work for that case:
because the redirection is handled outside of the sudo context.
I ended up using this instead:
The
cat <<EOF
syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.Examples of
cat <<EOF
syntax usage in Bash:1. Assign multi-line string to a shell variable
The
$sql
variable now holds the new-line characters too. You can verify withecho -e "$sql"
.2. Pass multi-line string to a file in Bash
The
print.sh
file now contains:3. Pass multi-line string to a pipe in Bash
The
b.txt
file containsbar
andbaz
lines. The same output is printed tostdout
.POSIX 7
kennytm quoted
man bash
, but most of that is also POSIX 7: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04 :Examples
Some examples not yet given.
Quotes prevent parameter expansion
Without quotes:
Output:
With quotes:
or (ugly but valid):
Outputs:
Hyphen removes leading tabs
Without hyphen:
where
<tab>
is a literal tab, and can be inserted withCtrl + V <tab>
Output:
With hyphen:
Output:
This exists of course so that you can indent your
cat
like the surrounding code, which is easier to read and maintain. E.g.:Unfortunately, this does not work for space characters: POSIX favored
tab
indentation here. Yikes.