Bash Here-Docs – How to Use Multiple Here-Docs in Bash

bashhere-documentio-redirection

Can one use multiple here-docs to provide input to a command in bash?

$ cat <<<foo <<<bar
bar
$ cat <<EOF1 <<EOF2
> foo
> EOF1
> bar
> EOF2
bar

Obviously, in both cases, the second here-doc is used as stdin, and replaces the first reference. Is the solution to use echos instead?

$ cat <(echo -n foo) <(echo bar)
foobar

Also, for some reason, using a combination didn't work for me. Why would that be?

$ cat <<<foo <(echo bar)
bar
$ cat <(echo -n foo) <<<bar
foo

Best Answer

You can do:

cat /dev/fd/3 3<< E1 /dev/fd/4 4<< E2
foo
E1
bar
E2

There can be only one stdin, as there's only one file descriptor 0.

cat << EOF
eof
EOF

is short for:

cat /dev/fd/0 0<< EOF
eof
EOF

And:

cat <<< foo

is:

cat /dev/fd/0 0<<< foo

You have to make up your mind what to open on file descriptor 0.

cat <(echo foo)

Is:

cat /dev/fd/123

Where 123 is a file descriptor to a pipe, and in parallel, bash runs echo foo in another process with the stdout redirected to the other end of the pipe.

Once you pass a filename to cat, cat no longer read from stdin. You'd need:

cat <(echo foo) /dev/fd/0 << EOF
bar
EOF

Or:

cat <(echo foo) - << EOF
bar
EOF

(- is to tell cat to read from stdin).

Related Question