Bash中单引号和双引号之间的区别

本文翻译自:Difference between single and double quotes in Bash

在bash,什么是单引号(之间的差异'' )和双引号( "" )?


#1楼

参考:https://stackoom.com/question/S6OH/Bash中单引号和双引号之间的区别


#2楼

The accepted answer is great. 公认的答案是伟大的。 I am making a table that helps in quick comprehension of the topic. 我正在制作一张有助于快速理解该主题的表格。 The explanation involves a simple variable a as 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 echo the expression in the second column, we would get the result / behavior shown in the third column. 然后echo显第二列中的表达式,我们将获得第三列中显示的结果/行为。 The fourth column explains the behavior. 第四列说明了行为。

 # | 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: 也可以看看:


#3楼

Others explained very well and just want to give with simple examples. 其他人解释得很好,只想举一些简单的例子。

Single quotes can 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. 当用单引号引起来时,美元符号,空格,&符,星号和其他特殊字符都将被忽略。

$ 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 quotes act 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. 它还允许转义双引号,因此不会将其解释为带引号的字符串的结尾。

$ 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 quotes are 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 

#4楼

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. 使用" " ,无论包围什么,都将“转换或转换”为其值。

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 $a on standard output. 示例: a=23 ,然后echo '$a'将在标准输出上产生$a Whereas echo "$a" will produce 23 on standard output. echo "$a"将在标准输出上产生23


#5楼

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 bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. bash shell支持两种执行算术运算的方式,一种是由内置的let命令和$((..))运算符定义的。 The former evaluates an arithmetic expression while the latter is more of a compound statement. 前者评估算术表达式,而后者则更多是复合语句。

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. 重要的是要理解, let所使用的算术表达式会像其他任何shell命令一样经历单词拆分和路径名扩展。 So proper quoting and escaping needs to be done. 因此,需要进行正确的引用和转义。

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 $bar under single quotes would not expand 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 . 这应该是原因之一, $((..))应始终被视为过度使用let Because inside it, the contents aren't subject to word-splitting. 因为在其中,内容无需分词。 The previous example using let can be simply written as 前面使用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 cannot contain 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. 在某些特殊情况下,可能需要在单引号字符串内使用$((..))运算符,您需要以不带引号或双引号的方式插入引号。 Eg consider a case, when you are tying to use the operator inside a curl statement 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 requestCounter field. 请注意,内部使用了嵌套的双引号,否则, $((reqcnt++))义字符串$((reqcnt++))传递给requestCounter字段。


#6楼

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 3.1.2.2单引号

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 3.1.2.3双引号

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. 将字符括在双引号( " )中会保留引号内所有字符的字面值,但$`\\和启用历史扩展的!除外。。字符$`在double内保留其特殊含义引号(请参阅Shell Expansions )仅在反斜杠后跟以下字符之一时才保留其特殊含义: $`"\\或换行符。 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 ). 在双引号中,特殊参数*@具有特殊含义(请参见Shell参数扩展 )。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值