Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How does “cat << EOF” work in bash?

I expected to compose a script to enter multi-line input to a program (psql).

After a touch of googling, I tracked down the accompanying sentence structure works:

cat << EOF | psql ---params
BEGIN;

`pg_dump ----something`

update table .... statement ...;

END;
EOF


This accurately builds the multi-line string (from BEGIN; to END;, comprehensive) and pipes it as an input to psql.

In any case, I have no clue about how/why it works, can somebody if it's not too much trouble, clarify?

I'm alluding primarily to cat << EOF, I know > outputs to a file, >> appends to a file, < reads input from file.

What does << precisely do?

Also, is there a man page for it?
by

2 Answers

ninja01
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:

$ sudo cat <<EOF >/etc/somedir/foo.conf
# my config file
foo=bar
EOF

because the redirection is handled outside of the sudo context.

I ended up using this instead:

$ sudo tee <<EOF /etc/somedir/foo.conf >/dev/null
# my config file
foo=bar
EOF
sandhya6gczb
Here is the example of cat<<EOF syntax usage
1. Assign multi-line string to a shell variable

$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

The $sql variable now holds the new-line characters too. You can verify with echo -e "$sql".

2. Pass multi-line string to a file in Bash

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user
3. Pass multi-line string to a pipe in Bash
$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

Login / Signup to Answer the Question.