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:

  1. 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
  2. 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.

  3. Use here-documents with other commands.
    $ mysql -u user -p <<EOF
    SHOW DATABASES;
    EOF

    Here-documents simplify feeding commands to interactive programs.

  4. 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.

  5. Combine variable expansion or command substitution as needed.

    Here-documents interpret variables by default, providing dynamic content insertion.

Discuss the article:

Comment anonymously. Login not required.