In this article, we will explore how we can use the cat command and the EOF feature to perform tasks such as writing multi-line strings to a file and more.
Writing Multi-Line String to a File
The cat command and the EOF feature provides us with a simple and intuitive way to writing multi-line strings to a file in Bash. You start by the cat command followed by a left shift operator.
Next, we add the keyword that will force Bash to terminate the input when encountered.
Finally, we pass a single redirection operator and the name of the file you wish to write.
An example syntax is as shown in the following:
> first line
> and another
> and another
Once Bash encounters the keyword EOF in the input, it terminates the input operation and write the provided contents to the file.
An example is as shown in the following:
> echo "Hello world"
In the previous example, we start by opening the multi-line operation and tell Bash to write the contents to the echo.sh file. This creates the file if it does not exist.
Finally, we write the multiple strings consecutively and press enter to proceed to the next line.
Once done, we can call the EOF string to terminate the input and write to file. We can verify by viewing the contents of the file.
echo "Hello world"
Using Cat EOF to Pipe Multi-Line String
When working with texts in Bash, you will encounter scenarios where you need to pipe a multi-line string to a command.
The cat and EOF feature can come in handy. In the following example, we use the cat and EOF command to pipe the multi-line string to grep.
The previous command takes all the input strings and pipe each one of them to grep. Grep then searches for matching strings and write them to apache.txt file.
The resulting output is as shown in the following:
In this article, we covered two main methods of using the cat command and EOF feature to write the multi-line string to a file and pipe the multi-line strings in Bash.