|
Here-documents (heredocs) let you include multi-line text directly in your script. They’re great for embedding configuration files, SQL queries, or help text. Basic syntax: The delimiter can be any word ( |
|
|
Output:
This is a here-document. It can span multiple lines. Variables like /root are expanded. |
|
|
Use |
|
|
Output:
This text is literal. $HOME is not expanded here. Special characters like \n are also literal. |
|
|
Use |
|
|
Output:
This line had a leading tab. So did this one. The tabs are stripped from output. |
|
|
Here-documents are commonly used with commands that read from stdin. Send mail (example - won’t actually send): |
|
|
Output:
message: Daily report attached. Generated on Wed Jan 1 10:00:00 UTC 2025. |
|
|
Create a configuration file file with a here-document by
adding a redirection operator |
|
|
Output:
Created config file: # Configuration file # Generated: Wed Jan 1 10:00:00 UTC 2025 setting1=value1 setting2=value2 debug=false |
|
|
Bash
Here-strings (<<<) provide a shorthand for passing a string directly to a command’s stdin: |
|
|
Output:
search in this string |
|
|
Bash
Here-strings are particularly useful with read: |
|
|
Output:
First word: hello |
|
|
Bash
They can include variable expansion: |
|
|
Output:
HELLO, WORLD! |
|
|
Here-documents work great for multi-line variables. |
|
|
Output:
Usage: myscript [options] <file> Options: -h, --help Show this help message -v, --verbose Enable verbose output -o FILE Output to FILE Examples: myscript input.txt myscript -v -o output.txt input.txt |
|