Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a dollar sign in Unix inside the cat command

Tags:

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.

like image 597
Iron Pillow Avatar asked Feb 24 '14 10:02

Iron Pillow


People also ask

How do you exit the dollar sign in Linux?

Dollar escaping: Provide means to escape $ in multiline strings. The nicest and the most natural way to do it is via the same \$ sequence as in single line strings (no need to learn new syntax), but it is a backwards-incompatible change that will take years to get gradually introduced.

How do you exit cat command in Unix?

We can see that whatever texts we've entered into the standard input stream will be echoed to the output stream by the cat command. Once we are done, we can terminate the command by pressing CTRL+D.

How do I show dollar signs in Linux?

The answer is to use either \$ or single quotes.


1 Answers

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.

like image 135
tripleee Avatar answered Sep 23 '22 21:09

tripleee