How To Cat EOF For Multi-Line String In Linux Bash?

The cat command is used to put given content to the specified output. If the content is a multiline string, text, or script putting it directly from the command line is a bit tedious. the “Here Documents” can be used to put content to the specified file in an interactive way. The cat, EOF, << is used to construct a multi-line string.

Put Multi-line String Into A File

The cat, EOF, << and > can be used to put the multi-line string into a file. This is an interactive way to input a string a file in the bash. The EOF is the heredoc which means the EOF is the end of the input. The > is used to redirect given content to the specified file. The << is used to set the end of the content marker which is EOF in this case. the mydata.txt is the file name where the input is written.

cat << EOF > mydata.txt
İsmail
Ahmet
Ali
EOF

Alternatively a script file can be created by using cat, EOF, <<, > .

cat << EOF > backup.sh
#!/bin/bash
tar cvf /home/ismail
EOF

Assign Multi-line String Into A Bash Variable

The cat, EOF, << can be used to assigne multi-line string into a bash variable. The string is printed by using the cat command and $() operator is used to assign as a bash variable.

comm =$(cat <<EOF
ls /home/ismail/Downloads/
rm /home/ismail/Downloads/*
EOF

Pass Multi-line String To A Pipe

Also the cat, EOF and pipe operator can be used to redirect given multi-line string to the specified pipe and command. In the following example speicfied content is grepped for the string “m” and the matched lines are redirected to the tee command in order to put content to the file names “matched_names.txt”.

cat <<EOF | grep 'm' | tee matched_names.txt
İsmail
Ahmet
Ali
Elif
Mehmet
EOF

Leave a Comment