Linux Commands


Cat is one of the most common and useful command-line utilities in the Linux ecosystem. It allows you to read or concatenate the contents of a file in a simple and easy to navigate manner. When combined with other tools such as awk, sed, less and more, cat can be one of the most powerful tools in your Linux arsenal.

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:

cat << EOF >
> 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:

cat << EOF >
> #!/bin/bash
> echo "Hello world"

In the previous example, we start by opening the multi-line operation and tell Bash to write the contents to the 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.

cat << EOF | grep 'apache' > apache.txt
apache kafka
apache webserver

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:

cat apache.txt
apache kafka
apache webserver



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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list