Bash中的单引号和双引号(转载)

来源:互联网 发布:233网校二级java视频 编辑:程序博客网 时间:2024/05/17 06:13

点击打开链接

1.1 单引号

Single quotes(‘’) are used to preserve the literal value of each character enclosed within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

也就是说,单引号内的所有字符都保持它本身字符的意思,而不会被bash进行解释, 例如,$就是$本身而不再是bash的变量引用符;\就是\本身而不再是bash的转义字符。 看下面的输出:

wangjk@wangjiankun:~$ cat single_quote.sh
1 #!/bin/bash
2
3 DATE='`date`'
4 echo "$DATE"
5 echo '$DATE'
6 echo '\$DATE'
7
8 echo
9 DATE="`date`"
10 echo "$DATE"
11 echo '$DATE'
12 echo '\$DATE'
wangjk@wangjiankun:~$ ./single_quote.sh
`date`
$DATE
\$DATE

Sun Jul 12 06:16:19 EDT 2009
$DATE
\$DATE
wangjk@wangjiankun:~$

1.2 双引号

Using double quotes the literal value of all characters enclosed is preserved, except for the dollar sign, the backticks(backward single quotes, ``) and the backslash.

The dollar sign and the backticks retain their special meaning within the double quotes.

The backslash retains its meaning only when followed by dollar, backtick, double quote, backslash or newline. Within double quotes, the backslashes are removed from the input stream when followed by one of these characters. Backslashes preceding characters that don’t have a special meaning are left unmodified for processing by the shell interpreter.

也就是说,除了$、``(不是单引号)和\外,双引号内的所有字符将保持字符本身的 含义而不被bash解释。$和``在双引号内,如果不被转义字符(\)转义,将无条件的 保持bash下的特殊含义,而转义字符(\)是有条件的。转义字符只有后跟$、``、双 引号、\和换行符五种特殊字符时才具有bash下的特殊含义:转义,换句话说,双引 号中只有以上五种字符可以被转义。如果在双引号中出现后跟非以上五种字符的\字 符,\就是\本身,没有什么特殊含义。


# x=* 
# echo $x 
hello.sh menus.sh misc.sh phonebook tshift.sh 
# echo '$x' 
$x 
# echo "$x" 


root@h0:~/bash_tools# echo hi\ \ \ hi
hi   hi
root@h0:~/bash_tools# echo hi   hi
hi hi


双引号在bash中称作partial quoting或者weak quoting,引号中的字符串很多不会被特殊转换,如:

  1. 空格作为词的分割符

  2. 单引号中的词

  3. 字符模式匹配

  4. 路径名扩展

  5. 进程替换 (重定向)

对于普通的字符,加不加双引号,单引号都一样

你想要看区别,可以尝试以下的一些例子:

a. touch "test me" 和 touch test me

b. echo "'$PATH'" 和 echo '$PATH'

c. echo "*" 和 echo *

d. ls "~" 和 ls ~

e.  ls "> out1" 和 ls > out1搜索

追问
想问一下var=1和var="1"有什么区别,因为用if [ var = 1 ]来判断时都为真,是不是和C语言中的意思有区别
回答
bash变量是没有类型的,整数1和字符“1”是一样的C语言1是整数,“1”是字符(串)

0 0
原创粉丝点击