简体   繁体   中英

Escaping a dollar sign in Unix inside the cat command

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, eg

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM