Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need cat to write a heredoc to a file?

Tags:

bash

cat

I've got a script that writes to a file, like so:

cat >myfile <<EOF
some lines
and more lines
EOF

but I'm not sure whether this is a Useless Use of Cat or not...

like image 294
Chani Avatar asked Jan 10 '13 22:01

Chani


People also ask

How do you use HereDoc?

To use here-document in any bash script, you have to use the symbol << followed by any delimiting identifier after any bash command and close the HereDoc by using the same delimiting identifier at the end of the text.

How does HereDoc work in bash?

A HereDoc is a multiline string or a file literal for sending input streams to other commands and programs. HereDocs are especially useful when redirecting multiple commands at once, which helps make Bash scripts neater and easier to understand.

How do you use EOF and cat?

cat with <<EOF>> will create or append the content to the existing file, won't overwrite. whereas cat with <<EOF> will create or overwrite the content.


3 Answers

Even if this may not be a UUOC, it might be useful to use tee instead:

tee myfile <<EOF
some lines
and more lines
EOF

It's more concise, plus unlike the redirect operator it can be combined with sudo if you need to write to files with root permissions.

like image 184
Livven Avatar answered Sep 30 '22 09:09

Livven


It is not really a UUOC. You can also do the same with echo:

echo "this is line
this is another line
this is the last line" > somefile
like image 32
jim mcnamara Avatar answered Sep 30 '22 07:09

jim mcnamara


UUOC is when you use cat when it is not needed. As in:

cat file | grep "something"

Instead you can do it whithout cat:

grep "something" file

Look here for the original definition of UUOC.

like image 45
jgr Avatar answered Sep 30 '22 08:09

jgr