A heredoc (here-document) is a feature in Unix-like operating systems that allows you to create a block of text that can be used as input for a command. It enables you to specify a multi-line string directly in your script or command line without needing to use multiple echo statements or other methods.
Syntax
The basic syntax for a heredoc is as follows:
command <<EOF
line 1
line 2
line 3
EOF
In this example:
commandis the command that will receive the input.<<EOFindicates the start of the heredoc, whereEOFis a delimiter that you can choose (it can be any string).- The lines between the start and end delimiters are treated as input to the command.
Example
Here’s a simple example using cat to display a multi-line string:
cat <<EOF
This is line 1.
This is line 2.
This is line 3.
EOF
When you run this, it will output:
This is line 1.
This is line 2.
This is line 3.
Use Cases
Heredocs are often used in scripts for:
- Providing multi-line input to commands.
- Creating configuration files or scripts dynamically.
- Writing documentation or comments within scripts.
Conclusion
Heredocs are a powerful feature for handling multi-line strings in shell scripting, making it easier to manage input without cluttering your code with multiple commands.
