Bash Here Documents
A here document is a block of text written inside a script and sent to a command. The block starts after <<EOF and ends at a line holding only EOF.
Sending a block of text
cat receives the two lines between the markers. It prints them exactly as written.
cat <<EOF
Hello there
Welcome to Bash
EOFVariables expand inside the block
The variable name holds the value Ana. The block prints that value in place of $name.
name="Ana"
cat <<EOF
Hello, $name!
Welcome back.
EOFQuoting the marker keeps dollars literal
The quoted 'EOF' switches expansion off for the block. The same $name now prints as plain text.
name="Ana"
cat <<'EOF'
Hello, $name!
Welcome back.
EOFExample
name="Ana"
city="Paris"
cat <<EOF
Trip plan for $name
City: $city
Day 1: Arrive and rest
Day 2: See the sights
EOFKey points
- Write <<EOF after a command to start the block.
- The lines after it go to the command as its input.
- A line holding only EOF ends the block.
- Variables inside the block expand to their values.
- Quoting the marker as 'EOF' stops that expansion.
- With a quoted marker, a $name in the block stays literal text.
In this example, two variables hold a name and a city for a trip plan. The here document sends four lines to cat in one block. Both variables expand inside the block, so the printed plan shows Ana and Paris.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a here document know where its block of text ends?