25

On Ubuntu, I would like to end up with a disk file that reads:

foo $(bar)

I would like to create this file using the cat command, e.g.

cat <<EOF > baz.txt
type_magic_incantation_here_that_will_produce_foo_$(bar)
EOF

The problem is the dollar sign. I have tried multiple combinations of backslash, single-quote, and double-quote characters, and cannot get it to work.

tripleee
  • 158,107
  • 27
  • 234
  • 292
Iron Pillow
  • 2,082
  • 4
  • 17
  • 29
  • Possible duplicate of [How to cat <> a file containing code? in shell](https://stackoverflow.com/questions/22697688/how-to-cat-eof-a-file-containing-code-in-shell) – tripleee Feb 16 '18 at 10:55

2 Answers2

48

You can use regular quoting operators in a here document:

$ cat <<HERE
> foo \$(bar)
> HERE
foo $(bar)

or you can disable expansion in the entire here document by quoting or escaping the here-doc delimiter:

$ cat <<'HERE'  # note single quotes
> foo $(bar)
> HERE
foo $(bar)

It doesn't matter whether you use single or double quotes or a backslash escape (<<\HERE); they all have the same effect.

tripleee
  • 158,107
  • 27
  • 234
  • 292
  • This is helpful, too. I didn't know these were called "here documents." – Iron Pillow Feb 24 '14 at 10:47
  • This is the better answer. I finally figured out that my problem arose because I had *nested* escapes that needed to be prevented. This is the cleaner solution. – Iron Pillow Feb 24 '14 at 21:47
3

Backslash ('\') works for me. I tried it and here is the output:

$ cat <<EOF > tmp.txt
foo \$(abc)
EOF

$ cat tmp.txt 
foo $(abc)

I tried it on bash. I'm not sure whether you have to use a different escape character in a different shell.

fedorqui
  • 252,262
  • 96
  • 511
  • 570
Vinay
  • 103
  • 9