How can I write a here document to a file in Bash script?
Read the Advanced Bash-Scripting Guide Chapter 19. Here Documents.
Here's an example which will write the contents to a file at /tmp/yourfilehere
cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
Note that the final 'EOF' (The LimitString
) should not have any whitespace in front of the word, because it means that the LimitString
will not be recognized.
In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <<-
(followed by a dash) to disable leading tabs (Note that to test this you will need to replace the leading whitespace with a tab character, since I cannot print actual tab characters here.)
#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
If you don't want to interpret variables in the text, then use single quotes:
cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
To pipe the heredoc through a command pipeline:
cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
Output:
foo
bbr
bbz
... or to write the the heredoc to a file using sudo
:
cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
-
14You don't even need Bash, this feature is in the Bourne/Korn/POSIX shells too. – Janus Troelsen May 1 '13 at 17:24
-
7
-
21@PineappleUndertheSea
<<<
are called 'Here Strings'. Code liketr a-z A-Z <<< 'one two three'
will result in the stringONE TWO THREE
. More information at en.wikipedia.org/wiki/Here_document#Here_strings – Stefan Lasiewski Dec 9 '13 at 18:03 -
9The final EOF should not have any whitespace after it either. At least on bash, this results in it being unrecognised as the delimiter – carpii Jul 12 '15 at 13:43
-
10Since this particular heredoc is intended to be literal content, rather than containing substitutions, it should be
<<'EOF'
rather than<<EOF
. – Charles Duffy May 27 '16 at 16:13
Instead of using cat
and I/O redirection it might be useful to use tee
instead:
tee newfile <<EOF
line 1
line 2
line 3
EOF
It's more concise, plus unlike the redirect operator it can be combined with sudo
if you need to write to files with root permissions.
-
23I'd suggest adding
> /dev/null
at the end of the first line to prevent the contents of the here file being displayed to stdout when it's created. – Joe Carroll Jun 19 '13 at 12:50 -
11True, but your solution appealed to me because of its compatibility with
sudo
, rather than because of its brevity :-) – Joe Carroll Jun 24 '13 at 13:32 -
2
-
7@MountainX Check out
man tee
. Use the-a
flag to append instead of overwrite. – Livven Jul 23 '13 at 17:47 -
3For use in a config script that I sometimes need to oversee, I like this one more because it prints the contents. – Alois Mahdal Jul 29 '13 at 18:12
Note:
- the following condenses and organizes other answers in this thread, esp the excellent work of Stefan Lasiewski and Serge Stroobandt
- Lasiewski and I recommend Ch 19 (Here Documents) in the Advanced Bash-Scripting Guide
The question (how to write a here document (aka heredoc) to a file in a bash script?) has (at least) 3 main independent dimensions or subquestions:
- Do you want to overwrite an existing file, append to an existing file, or write to a new file?
- Does your user or another user (e.g.,
root
) own the file? - Do you want to write the contents of your heredoc literally, or to have bash interpret variable references inside your heredoc?
(There are other dimensions/subquestions which I don't consider important. Consider editing this answer to add them!) Here are some of the more important combinations of the dimensions of the question listed above, with various different delimiting identifiers--there's nothing sacred about EOF
, just make sure that the string you use as your delimiting identifier does not occur inside your heredoc:
To overwrite an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:
cat << EOF > /path/to/your/file This line will write to the file. ${THIS} will also write to the file, with the variable contents substituted. EOF
To append an existing file (or write to a new file) that you own, substituting variable references inside the heredoc:
cat << FOE >> /path/to/your/file This line will write to the file. ${THIS} will also write to the file, with the variable contents substituted. FOE
To overwrite an existing file (or write to a new file) that you own, with the literal contents of the heredoc:
cat << 'END_OF_FILE' > /path/to/your/file This line will write to the file. ${THIS} will also write to the file, without the variable contents substituted. END_OF_FILE
To append an existing file (or write to a new file) that you own, with the literal contents of the heredoc:
cat << 'eof' >> /path/to/your/file This line will write to the file. ${THIS} will also write to the file, without the variable contents substituted. eof
To overwrite an existing file (or write to a new file) owned by root, substituting variable references inside the heredoc:
cat << until_it_ends | sudo tee /path/to/your/file This line will write to the file. ${THIS} will also write to the file, with the variable contents substituted. until_it_ends
To append an existing file (or write to a new file) owned by user=foo, with the literal contents of the heredoc:
cat << 'Screw_you_Foo' | sudo -u foo tee -a /path/to/your/file This line will write to the file. ${THIS} will also write to the file, without the variable contents substituted. Screw_you_Foo
-
#6 is best. But how do you overwrite contents of existing file with #6? – Aleksandr Makov Apr 21 '15 at 13:47
-
2@Aleksandr Makov: how do you overwrite contents of existing file with #6? Omit the
-a
==--append
; i.e.,tee -a
->tee
. Seeinfo tee
(I'd quote it here, but comment markup is too limited. – TomRoche Apr 22 '15 at 19:03 -
1Is there a benefit to #6 using cat and piping to tee instead of
sudo tee /path/to/your/file << 'Screw_you_Foo'
? – codemonkee Mar 10 '17 at 1:27 -
-
3@becko: just to illustrate that the label is just a label. Note that I used a different label in each example. – TomRoche Sep 1 '18 at 22:01
To build on @Livven's answer, here are some useful combinations.
variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<EOF ${variable} EOF
no variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<'EOF' ${variable} EOF
variable substitution, leading tab removed, overwrite file, echo to stdout
tee /path/to/file <<-EOF ${variable} EOF
variable substitution, leading tab retained, append to file, echo to stdout
tee -a /path/to/file <<EOF ${variable} EOF
variable substitution, leading tab retained, overwrite file, no echo to stdout
tee /path/to/file <<EOF >/dev/null ${variable} EOF
the above can be combined with
sudo
as wellsudo -u USER tee /path/to/file <<EOF ${variable} EOF
When root permissions are required
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF
-
Is it possible to pass variables to here documents? How could you get it so $FOO was interpreted? – user1527227 Jul 24 '14 at 17:03
-
Below I have attempted to combine and organize this answer with that of Stefan Lasiewski. – TomRoche Sep 18 '14 at 18:32
-
4@user1527227 Just don't enclose EOF in single quotes. Then $FOO will be interpreted. – imnd_neel Feb 1 '17 at 8:46
-
You can also use
| sudo cat >
instead of| sudo tee
if you don't want the input to be printed back to the stdout again. Of course, now you're usingcat
twice and doubly invoking that "unnecessary use of cat" meme, probably. – dynamitereed Feb 19 at 22:43
For future people who may have this issue the following format worked:
(cat <<- _EOF_
LogFile /var/log/clamd.log
LogTime yes
DatabaseDirectory /var/lib/clamav
LocalSocket /tmp/clamd.socket
TCPAddr 127.0.0.1
SelfCheck 1020
ScanPDF yes
_EOF_
) > /etc/clamd.conf
-
6Don't need the parentheses:
cat << END > afile
followed by the heredoc works perfectly well. – glenn jackman Jun 2 '10 at 0:12 -
Thanks, this actually solved another issue I ran into. After a few here docs there was some issues. I think it had to do with the parens, as with the advice above it fixed it. – Joshua Enfield Jun 7 '10 at 17:53
-
2This won't work. The output redirection needs to be at the end of the line which starts with
cat
as shown in the accepted answer. – Dennis Williamson May 1 '13 at 20:07 -
2@DennisWilliamson It works, that's what the parens are for. The whole
cat
runs inside a subshell, and all the output of the subshell is redirected to the file – Izkata Aug 15 '15 at 6:45 -
2@Izkata: If you look at the edit history of this answer, the parentheses were removed before I made my comment and added back afterwards. glenn jackman's (and my) comment applies. – Dennis Williamson Aug 15 '15 at 10:21
As instance you could use it:
First(making ssh connection):
while read pass port user ip files directs; do
sshpass -p$pass scp -o 'StrictHostKeyChecking no' -P $port $files $user@$ip:$directs
done <<____HERE
PASS PORT USER IP FILES DIRECTS
. . . . . .
. . . . . .
. . . . . .
PASS PORT USER IP FILES DIRECTS
____HERE
Second(executing commands):
while read pass port user ip; do
sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
COMMAND 1
.
.
.
COMMAND n
ENDSSH1
done <<____HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
____HERE
Third(executing commands):
Script=$'
#Your commands
'
while read pass port user ip; do
sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip "$Script"
done <<___HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
___HERE
Forth(using variables):
while read pass port user ip fileoutput; do
sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip fileinput=$fileinput 'bash -s'<<ENDSSH1
#Your command > $fileinput
#Your command > $fileinput
ENDSSH1
done <<____HERE
PASS PORT USER IP FILE-OUTPUT
. . . . .
. . . . .
. . . . .
PASS PORT USER IP FILE-OUTPUT
____HERE
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
I like this method for concision, readability and presentation in an indented script:
<<-End_of_file >file
→ foo bar
End_of_file
Where →      Â
is a tab character.