Here documents, often called "heredocs," are a powerful feature in Bash scripting. They provide a convenient way to include multiline strings or input in your scripts.
A here document is a type of redirection that allows you to pass multiple lines of input to a command. It's particularly useful when you need to include large blocks of text or complex input in your scripts.
The basic syntax for a here document is as follows:
command << DELIMITER
Your multiline content goes here
More lines of content
DELIMITER
The DELIMITER
can be any word you choose, but it's common to use EOF
(End Of File) or EOT
(End Of Text).
cat << EOF > myfile.txt
This is the first line.
Here's another line.
And one more for good measure.
EOF
This command creates a file named myfile.txt
with the specified content.
grep 'important' << EOT
This line is not important.
This line is very important!
Another unimportant line.
EOT
This example uses grep
to search for the word "important" in the provided text.
By default, Bash performs tab expansion in here documents. To prevent this, you can use <<-
instead of <<
:
cat <<- EOF
This line will have leading tabs removed.
This one too.
EOF
Here documents allow variable expansion by default. To disable it, quote the delimiter:
name="John"
cat << 'EOF'
Hello, $name!
EOF
This will output Hello, $name!
literally, without expanding the variable.
To further enhance your Bash scripting skills, consider exploring these related topics:
Here documents are a versatile tool in Bash scripting. They simplify the process of working with multiline text and can significantly improve the readability and maintainability of your scripts.