Skip to content
Advertisement

How to cat <> a file containing code?

I want to print code into a file using cat <<EOF >>:

JavaScript

but when I check the file output, I get this:

JavaScript

I tried putting single quotes but the output also carries the single quotes with it. How can I avoid this issue?

Advertisement

Answer

You only need a minimal change; single-quote the here-document delimiter after <<.

JavaScript

or equivalently backslash-escape it:

JavaScript

Without quoting, the here document will undergo variable substitution, backticks will be evaluated, etc, like you discovered.

If you need to expand some, but not all, values, you need to individually escape the ones you want to prevent.

JavaScript

will produce

JavaScript

As suggested by @fedorqui, here is the relevant section from man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

JavaScript

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence <newline> is ignored, and must be used to quote the characters , $, and `.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement