bash 在bashscript中转义美元符号(使用awk)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18344459/
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 06:18:52  来源:igfitidea点击:

escape dollar sign in bashscript (which uses awk)

bashawk

提问by One Two Three

I want to use awk in my bashscript, and this line clearly doesn't work:

我想在我的 bashscript 中使用 awk,而这一行显然不起作用:

line="foo bar"
echo $line | awk '{print }'

How do I escape $1, so it doesn't get replaced with the first argument of the script?

我如何转义$1,所以它不会被脚本的第一个参数替换?

采纳答案by cmbuckley

Your script (with single quotes around the awk script) will work as expected:

您的脚本(在 awk 脚本周围带有单引号)将按预期工作:

$ cat script-single
#!/bin/bash
line="foo bar"
echo $line | awk '{print }'

$ ./script-single test
foo

The following, however, willbreak (the script will output an empty line):

但是,以下内容中断(脚本将输出一个空行):

$ cat script-double
#!/bin/bash
line="foo bar"
echo $line | awk "{print }"

$ ./script-double test
?

Notice the double quotes around the awkprogram.

注意awk程序周围的双引号。

Because the double quotes expand the $1variable, the awk command will get the script {print?test}, which prints the contents of the awk variable test(which is empty). Here's a script that shows that:

因为双引号扩展了$1变量,awk 命令将获取 script {print?test},它打印 awk 变量的内容test(它是空的)。这是一个脚本,显示:

$ cat script-var
#!/bin/bash
line="foo bar"
echo $line | awk -v test=baz "{print }"

$ ./script-var test
baz

Related reading: Bash Reference Manual - Quotingand Shell Expansions

相关阅读:Bash 参考手册 - 引用Shell 扩展

回答by SheetJS

As currently written, the $1 will not be replaced (since it's within single-quoted string, bash will not parse it)

正如目前所写,$1 不会被替换(因为它在单引号字符串中,bash 不会解析它)

If you write awk "{print $1}", bash will expand the $1within the double-quoted string

如果你写awk "{print $1}",bash 将$1在双引号内展开

Note that the variable expansion rules depend on the outermost level of quoting, so the $1in "awk '{print $1}'"will be expanded

注意变量扩展规则依赖于最外层的引用,所以$1in"awk '{print $1}'"会被扩展