Creating a File with Contents in Bash


Read {count} times since 2020

It’s really easy to create a file in Bash with cat and > :

cat "/home/simsu/file.txt"
> "/home/simsu/file.txt"

But, what if you want to add contents to file too ? In this case, we can use cat and echo. Here’s how we do it in echo :

echo "My File, My Choice" > "/home/simsu/file.txt"

But, there’s a problem with doing like this. Since there is an option to limit the characters of a Terminal command, adding large contents is not possible. In this case, we need to use cat.

The usage is very simple and can have different kinds of quotes and the ending of the contents is determined by a string you mention.

cat > /home/simsu/file.txt << ENDOFFILE
My File, My Choice
I have the right to write what I want in this file
and no NSA can stop me from doing it.
	I had privacy before NSA and the whole internet
and now I'm just a tiny little book that was read
by everyone....
ENDOFFILE

In the above case, we tell cat to add the contents until the string “ENDOFFILE” comes up. This ending string is mentioned in the first line as well as at the ending of the contents.

Since, we don’t use any quotes, you can use quotes in the content without any syntax problem at all.

Note that the ending string you mentioned should only occur at the end of the contents. Otherwise, the full content won’t be added to the file.