Linux is a great tool among coders, known for its flexibility and power. Yet, hidden within its command-line interface was a common challenge that tested developers: writing to a file.
For the eager developer, this task began as straightforward, but quickly turned into a quest filled with obstacles. Tools like echo
and cat
required deft handling to avoid overwriting data or mishaps.
The nuances of redirection (with >
and >>
) further confounded beginners, with minor mistakes leading to accidental data loss or empty files, reflecting erroneous commands.
This was the pain developers faced—a rite of passage through Linux's demanding landscape. But let me show you, with tutotial, how to effectively write in a file using Linux command cat.
What is cat <<EOL?
This is called heredoc format to provide a string into stdin. And in this case EOL is know as a "Here Tag".
How does it work?
Basically <<Here
tells the shell that you are going to enter a multiline string until the "tag" Here
. You can name this tag as you want, it's often EOF
or STOP
.
Some rules about the Here tags:
- The tag can be any string, uppercase or lowercase, though most people use uppercase by convention.
- The tag will not be considered as a Here tag if there are other words in that line. In this case, it will merely be considered part of the string. The tag should be by itself on a separate line, to be considered a tag.
- The tag should have no leading or trailing spaces in that line to be considered a tag. Otherwise it will be considered as part of the string.
Write in a file using CAT <<EOL
To write to a file using cat <<EOL
in a Linux shell script and add a line break before appending new text, you can follow these examples:
Case 1: Writing to an Empty File
For an empty file, simply add new content:
#!/bin/bash
# Name of the file to write to
FILE="example.txt"
# Check if file exists and is empty
if [ ! -s "$FILE" ]; then
echo "File is empty or does not exist. Adding content to $FILE."
fi
# Use a Here Document to add content
cat <<EOL > "$FILE"
This is a new line of text.
Another line of text.
EOL
Case 2: Appending to a File that Already Contains Text with a Line Break
If the file already contains text, append new content with a preceding line break:
#!/bin/bash
# Name of the file to write to
FILE="example.txt"
# Check if file exists and has content
if [ -s "$FILE" ]; then
echo "File exists and is not empty. Appending content to $FILE."
# Add a line break before appending new text
echo "" >> "$FILE"
fi
# Use a Here Document to append content
cat <<EOL >> "$FILE"
This is an additional line of text.
Appending another line.
EOL
More notes
echo "" >> "$FILE"
is used to add a line break before appending new text.> "$FILE"
is used for overwriting in the first case.>> "$FILE"
is used for appending in the second case.- The
s
flag checks if the file is non-empty.