bash 在 cat 命令中转义 Unix 中的美元符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21984960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:40:16  来源:igfitidea点击:

Escaping a dollar sign in Unix inside the cat command

bashshellunixescapingsh

提问by Iron Pillow

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

在 Ubuntu 上,我想最终得到一个磁盘文件,内容如下:

foo $(bar)

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

我想使用cat命令创建这个文件,例如

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.

问题是美元符号。我尝试了反斜杠、单引号和双引号字符的多种组合,但无法正常工作。

回答by tripleee

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:

或者您可以通过引用或转义 here-doc 分隔符来禁用整个 here 文档中的扩展:

$ 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.

使用单引号还是双引号或反斜杠转义符 ( <<\HERE)都没有关系;它们都具有相同的效果。

回答by Vinay

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.

我在 bash 上试过了。我不确定您是否必须在不同的 shell 中使用不同的转义字符。