How to Cat EOF in Bash

Fumbani Banda Feb 02, 2024
  1. Cat EOF in Bash
  2. Put a Multi-line String to a File in Bash
  3. Pass Multi-line String to Pipe in Bash
How to Cat EOF in Bash

This tutorial explains what cat EOF is and its usage in bash.

Cat EOF in Bash

cat is a bash command used to read, display, or concatenate the contents of a file, while EOF stands for End Of File. The EOF is an indication to the shell that the file that was being read has ended. cat << eof uses here-document. The redirection operators << and <<- both allow redirection of subsequent lines read by the shell to the input of a command. The redirected lines are called here-document.

The here-document uses the following format.

[n] << word
     here-document
delimeter

The here-document is treated as a single word that begins after the next newline. It continues until there is a line containing only the delimiter or a new line with no blank characters in between.

Put a Multi-line String to a File in Bash

cat, <<, EOF, and > provide an interactive way to input a multi-line string into a file. The EOF is known as the Here Tag. The Here Tag tells the shell that you will input a multi-line string until the Here Tag. The << is used to set the Here Tag. The > is used to redirect the input content to a specified file, multiline.txt in our case.

cat << EOF > multiline.txt
> This is the first line
> This is the second line
> This is the third line
> EOF

We can also use cat, <<, EOF, and > to write bash scripts as shown below interactively.

cat << EOF > script.sh
#!/bin/bash

printf "Hello\n"
printf "Wordl!\n"
EOF

Pass Multi-line String to Pipe in Bash

The code below uses cat, eof, and pipe to redirect multi-line input string content to a specified pipe and command. The input is piped to the grep command which greps for string A and the matched input is piped to the tee command. The tee command copies the input to the fruits.txt file.

cat <<EOF | grep 'A' | tee fruits.txt
> Apple
> Orange
> Apricot
> Banana
> EOF

Let’s check the content of the fruits.txt file with cat.

cat fruits.txt

Output:

Apple
Apricot
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Bash Cat