Bash中单引号和双引号之间的区别
在Bash中,单引号( ''
)和双引号( ""
)之间有什么区别?
单引号不会插入任何内容,但双引号将会。 例如:变量,反引号,某些转义等。
例:
$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")
Bash手册有这样的说法:
3.1.2.2单引号
用单引号( '
)括起字符保留引号内每个字符的字面值。 单引号之间可能不会出现单引号,即使前面加了反斜线。
3.1.2.3双引号
用双引号( "
)括起来的字符保留了引号中所有字符的字面值,除了$
, `
, ,并且当启用历史扩展时,
!
。。字符$
和`
保留它们在双精度内的特殊含义引号(参见Shell Expansions)。只有当后面跟有以下字符之一时,反斜线才会保留其特殊含义: $
, `
, "
, 或newline。 在双引号内,删除后跟其中一个字符的反斜杠。 没有特殊含义的字符之前的反斜杠未作修改。 双引号可以用双引号括起来,前面加一个反斜杠。 如果启用,历史扩展将被执行,除非一个
!
出现在双引号中使用反斜线进行转义。 !
之前的反斜杠!
不会被删除。
使用双引号时,特殊参数*
和@
具有特殊含义(请参见壳参数扩展)。
如果你指的是当你回应某些事情时会发生什么,那么单引号将会回应你在它们之间的内容,而双引号将会评估它们之间的变量并输出变量的值。
例如,这个
#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'
会给这个:
double quotes gives you sometext
single quotes gives you $MYVAR
接受的答案很好。 我正在制作一张有助于快速理解该主题的表格。 解释涉及一个简单的变量a
以及一个索引数组arr
。
如果我们设置
a=apple # a simple variable
arr=(apple) # an array with a single element
然后在第二列中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 ""
10 | """ | " | " is interpreted inside ""
11 | "*" | * | glob does not work inside "" or ''
12 | "tn" | tn | 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 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"
---+-------------+-------------+--------------------------------------------------------------------
也可以看看:
$''
- GNU Bash手册 $""
语言环境翻译 - GNU Bash手册 上一篇: Difference between single and double quotes in Bash
下一篇: How to use double or single brackets, parentheses, curly braces