Reputation: 413
I know there are lots of posts in here about heredocs and also redirects and file descriptors, but I can't seem to find anything related to what I want to do.
I want to open a file descriptor to a file and then write a heredoc to that file descriptor.
Here's what I have using bash shell:
exec 3>/tmp/testfile.txt
cat <<EOF>>3
write to fd using heredoc
EOF
I check my file and its empty. I'm assuming its empty because the reference to my file descriptor in the heredoc goes to the bit bucket. I tried using an ampersand &
like this EOF>>&3
but that throws an error in the shell.
How can I get this accomplished?
Upvotes: 3
Views: 1876
Reputation: 413
OK here's the answer:
exec 3>/tmp/testfile.txt
cat <<EOF 1>&3
this is a redirect to fd 3 via a heredoc
EOF
Upvotes: 2
Reputation: 753835
The Bash manual for append redirection says:
The general format for appending output is:
[n]>>word
You appended to a file 3
. However, in practice, you don't need the >>
operator; you need to send the standard output of cat
to descriptor 3:
cat <<EOF 1>&3
write to fd using heredoc
EOF
This won't truncate the file, so it achieves 'append' anyway.
Upvotes: 0
Reputation: 311615
If you write:
echo something >> 3
This will create a filed called 3
. If you want to refer to a file descriptor, you need to use the &3
syntax. If you want to append to a file using a file descriptor, you can do this:
exec 3>>/tmp/testfile.txt
cat <<EOF >&3
This is a test.
EOF
That is, you decide append vs. overwrite when you open the file descriptor with the exec
statement. If you did this instead:
exec 3>/tmp/testfile.txt
That would overwrite the file rather than appending to it.
Upvotes: 4