In Bash, here-documents enable multiline input to be written directly into a script. This approach removes the need for external files or repetitive echo commands, streamlining content management. The content is fed to commands as though it were sourced from a file, offering a more organized and readable scripting workflow.
By using « followed by a chosen delimiter such as EOF, script authors can include configuration data, interactive prompts, and structured text inline. This allows for advanced features like variable expansion and command substitution, while minimizing external dependencies. Proper delimiter handling and quoting techniques prevent unwanted parsing issues.
Mastering here-documents promotes script portability and ensures straightforward content insertion. It also improves maintainability by consolidating data in one place, eliminating multiple file references. Techniques such as tab stripping with «- further enhance script clarity and control over whitespace.
Steps to use here-documents in Bash:
- Create a script using a here-document.
$ cat heredoc.sh #!/usr/bin/env bash cat <<EOF This is line one This is line two EOF
- Run the script and observe the output.
$ ./heredoc.sh This is line one This is line two
Everything between «EOF and EOF is treated as input to cat.
- Use here-documents with other commands.
$ mysql -u user -p <<EOF SHOW DATABASES; EOF
Here-documents simplify feeding commands to interactive programs.
- Indent text with «-EOF to allow tab stripping.
cat <<-EOF This line has leading tabs removed. EOF
Ensure the delimiter matches exactly to avoid unexpected behavior.
- Combine variable expansion or command substitution as needed.
Here-documents interpret variables by default, providing dynamic content insertion.

Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
Comment anonymously. Login not required.