Bash Here Documents
What is a Here Document?
A here document (heredoc) lets you write several lines of text directly in your script and send them to a command as input.
It starts with << followed by a word you choose (often EOF), and ends with a line that has only that word.
Basic Usage
Example: Print Several Lines
Save this as heredoc.sh:
#!/bin/bash
cat << EOF
Line one
Line two
Line three
EOF
Run it:
./heredoc.sh
Line one
Line two
Line three
Variables in a Here Document
Variables and commands inside a heredoc are replaced with their values:
Example: Use Variables
Save this as welcome.sh:
#!/bin/bash
name="Emma"
cat << EOF
Hello, $name!
You have $((2 + 3)) new messages.
EOF
Run it:
./welcome.sh
Hello, Emma!
You have 5 new messages.
Turn Off Replacement
Put the first word in quotes ('EOF') to keep the text exactly as written, with no variables replaced:
Example: Quoted Delimiter
Save this as literal.sh:
#!/bin/bash
name="Emma"
cat << 'EOF'
Hello, $name!
EOF
Run it:
./literal.sh
Hello, $name!
Write a File with a Here Document
Combine a heredoc with > to create a file with several lines in one step:
Example: Create a Config File
Save this as config.sh:
#!/bin/bash
cat << EOF > config.txt
host=localhost
port=8080
EOF
cat config.txt
Run it:
./config.sh
host=localhost
port=8080
Indented Here Documents (<<-)
Use <<- to remove tab characters at the start of each line. This lets you indent the heredoc in your script, for example inside an if block.
Only tab characters are removed, not spaces.
Here Strings (<<<)
A here string (<<<) sends a single string to a command as input:
Example: Here String
Save this as herestring.sh:
#!/bin/bash
tr "a-z" "A-Z" <<< "hello world"
wc -w <<< "one two three"
Run it:
./herestring.sh
HELLO WORLD
3