Home > Back-end >  cat to combine heredoc and file
cat to combine heredoc and file

Time:07-12

I'm trying to and failing to understand why this doesn't work. I'm trying to use cat to combine an existing file and a heredoc into one file:

# test.txt
Hi there
$ cat test.txt <<END > /tmp/combined.txt
This is heredoc
END

I would have expected this to function in essence like:

cat file.txt file1.txt > /tmp/combined.txt

But what I actually see is just the contents of test.txt:

#/tmp/combined.txt
Hi there

If I do just the heredoc it works. If i do just the file it works obviously. What is it about combining them that makes cat ignore the heredoc?

(I know I can use tee and a variety of other approaches to do this but I want to fill in my understanding of cat, redirection etc)

CodePudding user response:

cat echos the contents of its input filename arguments or standard input if none are given, but not both. However, if one of the arguments is -, that one is treated as reading from standard input:

$ cat test.txt - <<EOF
This is heredoc
EOF
Hi there
This is heredoc
  • Related