0
0
Bash Scriptingscripting~5 mins

Here documents (<<EOF) in Bash Scripting

Choose your learning style9 modes available
Introduction
Here documents let you send multiple lines of text or commands to a program easily without typing them one by one.
You want to provide input to a command that reads from standard input.
You need to create a multi-line text file quickly inside a script.
You want to run multiple commands inside another command like ssh or ftp.
You want to write a block of text to a file without using echo many times.
Syntax
Bash Scripting
<<EOF
Your text or commands here
EOF
EOF is a marker and can be any word, but it must match at start and end.
No spaces or tabs allowed before the ending marker (EOF) on its line.
Examples
Sends two lines 'Hello' and 'World' to the cat command which prints them.
Bash Scripting
cat <<EOF
Hello
World
EOF
Uses 'END' instead of 'EOF' as the marker. It works the same way.
Bash Scripting
cat <<END
Line 1
Line 2
END
Single quotes around EOF prevent variable expansion inside the here document.
Bash Scripting
cat <<'EOF'
$HOME is not expanded here
EOF
Sample Program
This script writes two lines into greetings.txt using a here document, then prints the file content.
Bash Scripting
#!/bin/bash
cat <<EOF > greetings.txt
Hello, friend!
Welcome to scripting.
EOF
cat greetings.txt
OutputSuccess
Important Notes
Make sure the ending marker (EOF) is alone on its line with no spaces or tabs before it.
If you quote the marker like <<'EOF', variables inside won't change to their values.
Here documents are great for feeding input to commands that expect typed input.
Summary
Here documents let you send multiple lines of text or commands easily.
Use <
You can prevent variable expansion by quoting the marker like <<'EOF'.