To use a Here Document (heredoc) in Bash, you need to follow a specific syntax. Here’s an example that demonstrates how to use a heredoc in different scenarios:
- Assigning Heredoc to a Variable:
variable=$(cat <<END
This is a heredoc example.
It assigns multiline text to a variable.
END
)
echo "$variable"
In this example, the heredoc text enclosed between <<END
and END
is assigned to the variable variable
. The cat
command is used to capture the heredoc text. Finally, the value of the variable is printed using echo
.
- Providing Input to a Command:
wc -l <<END
This is line 1.
This is line 2.
This is line 3.
END
In this example, the heredoc text is provided as input to the wc -l
command, which counts the number of lines. The output will display the number of lines in the heredoc text.
- Redirecting Heredoc to a File:
cat <<END > output.txt
This is line 1.
This is line 2.
This is line 3.
END
In this example, the heredoc text is redirected to a file called output.txt
using the >
redirection operator. The cat
command reads the heredoc text and writes it to the file.
Note that the END
delimiter used in the heredoc examples can be replaced with any word you choose, as long as it’s consistent for the opening and closing delimiters.
Heredocs are versatile and can be used in various scenarios where you need to provide multiline input, assign text to variables, pass input to commands, or redirect content to files. They provide a convenient way to include large blocks of text within a script without the need for external files or complex concatenation.