bash Bash中单引号和双引号的区别

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

Difference between single and double quotes in Bash

bashshellsyntaxquotes

提问by jrdioko

In Bash, what are the differences between single quotes ('') and double quotes ("")?

在 Bash 中,单引号 ( '') 和双引号 ( "") 有什么区别?

回答by Adam Batkin

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \escapes, etc.

单引号不会插入任何内容,但双引号会。例如:变量、反引号、某些\转义等。

Example:

例子:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

Bash 手册是这样说的:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $and `retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an !appearing in double quotes is escaped using a backslash. The backslash preceding the !is not removed.

The special parameters *and @have special meaning when in double quotes (see Shell Parameter Expansion).

3.1.2.2 单引号

将字符括在单引号 ( ') 中会保留引号内每个字符的字面值。单引号之间不能出现单引号,即使前面有反斜杠。

3.1.2.3 双引号

用双引号 ( ") 将字符括起来会保留引号内所有字符的字面值,但$, `, \, 和当启用历史扩展时,!. 双引号内的字符$`保留其特殊含义(请参阅Shell Expansions)。反斜杠仅在后跟以下字符之一时保留其特殊含义:$, `, ",\,或换行符。在双引号内,后跟这些字符之一的反斜杠将被删除。没有特殊含义的字符前面的反斜杠保持不变。双引号可以通过在双引号前面加上反斜杠来引用。如果启用,将执行历史扩展,除非!使用反斜杠转义双引号中的出现。前面的反斜杠!不会被删除。

双引号中的特殊参数*@具有特殊含义(请参阅Shell 参数扩展)。

回答by codeforester

The accepted answeris great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable aas well as an indexed array arr.

接受的答案是伟大的。我正在制作一个有助于快速理解该主题的表格。解释涉及一个简单的变量a以及一个索引数组arr

If we set

如果我们设置

a=apple      # a simple variable
arr=(apple)  # an indexed array with a single element

and then echothe expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.

然后echo是第二列中的表达式,我们将得到第三列中显示的结果/行为。第四列解释了行为。

 # | Expression  | Result      | Comments
---+-------------+-------------+--------------------------------------------------------------------
 1 | "$a"        | apple       | variables are expanded inside ""
 2 | '$a'        | $a          | variables are not expanded inside ''
 3 | "'$a'"      | 'apple'     | '' has no special meaning inside ""
 4 | '"$a"'      | "$a"        | "" is treated literally inside ''
 5 | '\''        | **invalid** | can not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting)
 6 | "red$arocks"| red         | $arocks does not expand $a; use ${a}rocks to preserve $a
 7 | "redapple$" | redapple$   | $ followed by no variable name evaluates to $
 8 | '\"'        | \"          | \ has no special meaning inside ''
 9 | "\'"        | \'          | \' is interpreted inside "" but has no significance for '
10 | "\""        | "           | \" is interpreted inside ""
11 | "*"         | *           | glob does not work inside "" or ''
12 | "\t\n"      | \t\n        | \t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13 | "`echo hi`" | hi          | `` and $() are evaluated inside ""
14 | '`echo hi`' | `echo hi`   | `` and $() are not evaluated inside ''
15 | '${arr[0]}' | ${arr[0]}   | array access not possible inside ''
16 | "${arr[0]}" | apple       | array access works inside ""
17 | $'$a\''     | $a'         | single quotes can be escaped inside ANSI-C quoting
18 | "$'\t'"     | $'\t'       | ANSI-C quoting is not interpreted inside ""
19 | '!cmd'      | !cmd        | history expansion character '!' is ignored inside ''
20 | "!cmd"      | cmd args    | expands to the most recent command matching "cmd"
21 | $'!cmd'     | !cmd        | history expansion character '!' is ignored inside ANSI-C quotes
---+-------------+-------------+--------------------------------------------------------------------


See also:

也可以看看:

回答by likso

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

如果您指的是当您回显某些内容时会发生什么,单引号将逐字地回显它们之间的内容,而双引号将评估它们之间的变量并输出变量的值。

For example, this

例如,这

#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'

will give this:

会给这个:

double quotes gives you sometext
single quotes gives you $MYVAR

回答by Sree

Others explained very well and just want to give with simple examples.

其他人解释得很好,只想举个简单的例子。

Single quotescan be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

可以在文本周围使用单引号以防止 shell 解释任何特殊字符。美元符号、空格、与号、星号和其他特殊字符在用单引号括起来时都会被忽略。

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

它会给这个:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

唯一不能放在单引号内的是单引号。

Double quotesact similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

双引号的作用类似于单引号,除了双引号仍然允许 shell 解释美元符号、反引号和反斜杠。众所周知,反斜杠会阻止解释单个特殊字符。如果需要将美元符号用作文本而不是变量,这在双引号内很有用。它还允许对双引号进行转义,因此它们不会被解释为带引号的字符串的结尾。

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

它会给这个:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

还可能会注意到,在双引号内忽略了单引号,否则会被解释为带引号的字符串的开头。但是,变量被解释并替换为双引号内的值。

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

它会给这个:

The current Oracle SID is test

Back quotesare wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

反引号完全不同于单引号或双引号。反引号不是用来阻止特殊字符的解释,而是实际上强制执行它们所包含的命令。执行所包含的命令后,它们的输出将替换原始行中的反引号。举个例子会更清楚。

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

它会给这个:

Monday, September 28, 2015 

回答by a_r

There is a clear distinction between the usage of ' 'and " ".

' '和的用法有明显区别" "

When ' 'is used around anything, there is no "transformation or translation" done. It is printed as it is.

' '用于任何事物时,没有完成“转换或翻译”。它按原样打印。

With " ", whatever it surrounds, is "translated or transformed" into its value.

With " ",无论它包围什么,都被“翻译或转化”为它的价值。

By translation/ transformation I mean the following: Anything within the single quotes will not be "translated" to their values. They will be taken as they are inside quotes. Example: a=23, then echo '$a'will produce $aon standard output. Whereas echo "$a"will produce 23on standard output.

通过翻译/转换,我的意思是:单引号内的任何内容都不会“翻译”为其值。它们将被视为在引号内。示例:a=23,然后echo '$a'$a在标准输出上产生。而echo "$a"23在标准输出上生产。

回答by Inian

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

由于这是处理 中的引号时的事实答案bash,因此在处理 shell 中的算术运算符时,我将补充上述答案中遗漏的一点。

The bashshell supports two ways do arithmetic operation, one defined by the built-in letcommand and the $((..))operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

bash外壳支持两种方式做算术运算,一个定义的内置let命令和$((..))操作。前者计算算术表达式,而后者更像是复合语句。

It is important to understand that the arithmetic expression used with letundergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

重要的是要理解使用 with 的算术表达式let像任何其他 shell 命令一样经历分词、路径名扩展。因此需要进行适当的引用和转义。

See this example when using let

使用时请参阅此示例 let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

在这里使用单引号绝对没问题,因为这里不需要变量扩展,请考虑以下情况

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $barunder single quotes would notexpand and needs to be double-quoted as

会失败,因为$bar下单引号不会扩展,需要双引号作为

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..))should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using letcan be simply written as

这应该是原因之一,$((..))应该始终考虑过度使用let. 因为在里面,内容不受分词的影响。前面使用的例子let可以简单地写成

(( bar=1, foo = bar + 1 ))

Always remember to use $((..))without single quotes

永远记住不要使用$((..))单引号

Though the $((..))can be used with double-quotes, there is no purpose to it as the result of it cannotcontain a content that would need the double-quote. Just ensure it is not single quoted.

虽然$((..))可以与双引号一起使用,但它没有任何意义,因为它不能包含需要双引号的内容。只要确保它不是单引号。

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..))operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curlstatement to pass a counter every time a request is made, do

可能在某些$((..))在单引号字符串中使用运算符的特殊情况下,您需要以运算符不加引号或双引号的方式插入引号。例如,考虑一种情况,当您在curl每次发出请求时都想在语句中使用运算符来传递计数器时,请执行以下操作

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++))is passed to requestCounterfield.

注意在内部使用了嵌套的双引号,没有它的文字字符串$((reqcnt++))被传递给requestCounter字段。