Here-Documents (<<EOF)
In this page:
A Basic Here-Document
<<DELIM starts a here-document; everything until a line containing exactly DELIM becomes the stdin of the preceding command. This is a clean way to embed multi-line text without a pile of echo calls.
Example: A Basic Here-Document
#!/bin/bash
cat <<EOF
Line one
Line two
Line three
EOF
Login to try C/C++/Java/PHP code in the editor
Variable Expansion Inside a Here-Document
By default, variables and command substitutions inside a here-document are expanded just like in double quotes. Quoting the delimiter, e.g. <<EOF, disables that expansion and treats the block as literal text.
Example: Variable Expansion Inside a Here-Document
#!/bin/bash
name="Ada"
cat <<EOF
Hello, $name!
Today is a scripted day.
EOF
echo "---"
cat <<'EOF'
This $name will NOT be expanded.
EOF
Login to try C/C++/Java/PHP code in the editor
Generating a File with a Here-Document
Redirecting a here-document into a file is a common way to generate configuration files or templates from within a script.
Example: Generating a File with a Here-Document
#!/bin/bash
cat > config.txt <<EOF
host=localhost
port=8080
EOF
cat config.txt
rm -f config.txt
Login to try C/C++/Java/PHP code in the editor
Indented Here-Documents with <<-
<<-DELIM strips leading tab characters (not spaces) from each line, including the closing delimiter, so you can indent a here-document to match the surrounding code inside a function.
Warning: <<- strips leading tabs only, not spaces, so mixing spaces and tabs will break the trick.
Example: Indented Here-Documents with <<-
#!/bin/bash
show_message() {
cat <<-EOF
This line was indented with a tab.
So was this closing delimiter.
EOF
}
show_message
Login to try C/C++/Java/PHP code in the editor
- Forgetting that the closing delimiter (like
EOF) must be on its own line with no leading whitespace unless you use<<-. - Not realizing variables and command substitutions inside a here-document are expanded by default, which can be surprising if you wanted literal text.
- Mismatching the opening and closing delimiter names, which makes bash keep reading the rest of the script as part of the here-document.
<<DELIM ... DELIMfeeds everything in between as stdin to a command.- Quoting the delimiter (
<<EOF) disables variable expansion inside the block. <<-EOFallows the closing delimiter to be indented with tabs, useful inside indented functions.- Here-documents are commonly used to generate config files or multi-line messages.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null