Using CAT And Bash Redirection To Write To Files

In this post I will show you how to use bash redirection to write to a file using the cat command. This is a very simple trick that you can use for all sorts of things when it comes to bash scripting including setting up certain configuration files when more powerful options aren’t available or aren’t worth using. You can also use this in your bash scripts to create files from scratch if need be without having to have separate files or download them remotely.

Here is a quick example of how this bash redirection trick works:

#!/bin/bash

cat << EOF > /path/to/file # Replace > with >> to add to file instead of replace
This is all
text that will
go into the
file we specified
EOF # This tells cat that there are no more lines

Another thing that you can do with this is actually pass variables directly into the file, here is a quick and simple example of doing so.

#!/bin/bash

myhostname=$(hostname);

cat << EOF > /path/to/file # Replace > with >> to add to file instead of replace

My hostname is: $myhostname
This is all
text that will
go into the
file we specified

EOF # This tells cat that there are no more lines

Sadly this doesn’t actually give you a confirmation if the file write was successful, to do that we can modify the first line a tiny bit. We will be using the && argument meaning if the last command succeeded then do this, as-well as the || argument which means if the last argument failed then do this instead.

#!/bin/bash

cat << EOF > /path/to/file && echo "Write succeeded." || echo "Write failed!" # Success or failure message added
This is all
text that will
go into the
file we specified
EOF # This tells cat that there are no more lines

I hope this quick and easy post will prove useful for you, please don’t forget to like/comment/share. Thanks for the support!

Leave a Reply

Your email address will not be published. Required fields are marked *