您的位置:首页 > 运维架构 > Shell

SHELL的单引号'',双引号"",及$字符单双引号及字符转义的小结

2010-07-22 13:39 423 查看
在shell运行命令中,单双引号总能引起或多或少的话题讨论,这边做个小总结

先看以下例子:

sosodream@ubuntu:~>echo '/t'|xxd
+ xxd
+ echo '/t'
0000000: 5c74 0a                                  /t.
sosodream@ubuntu:~>echo -e '/t'|xxd
+ xxd
+ echo -e '/t'
0000000: 090a                                     ..
sosodream@ubuntu:~>echo $'/t'|xxd
+ xxd
+ echo '        '
0000000: 090a                                     ..
sosodream@ubuntu:~>echo -e $'/t'|xxd
+ xxd
+ echo -e '     '
0000000: 090a                                     ..
sosodream@ubuntu:~>echo "/t"|xxd
+ xxd
+ echo '/t'
0000000: 5c74 0a                                  /t.
sosodream@ubuntu:~>echo -e "/t"|xxd
+ xxd
+ echo -e '/t'
0000000: 090a                                     ..
sosodream@ubuntu:~>echo  $"/t"|xxd
+ xxd
+ echo '/t'
0000000: 5c74 0a                                  /t.
sosodream@ubuntu:~>echo -e  $"/t"|xxd
+ xxd
+ echo -e '/t'
0000000: 090a                                     ..
sosodream@ubuntu:~>


实际上,分析单双引号,要从二个层面上去考虑以上边的例子:

第一层:shell传递参数给echo前进行的扩展解析
第二层:echo接受参数,处理,显示结果

具体分析如下:

第一层:shell传递参数给echo前进行的扩展解析

单引号:shell单引号不进行字符转义
原文:Enclosing characters in single quotes preserves the literal value of each character within the quotes.
双引号:不进行字符转义,除了三个字符$, `, /,和开启命令扩展后的!字符

$加单引号(即$''):除了以下字符转义,其他同单引号
/a alert (bell)
/b backspace
/e an escape character
/f form feed
/n new line
/r carriage return
/t horizontal tab
/v vertical tab
// backslash
/' single quote
/nnn the eight-bit character whose value is the octal value nnn (one to three digits)
/xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
/cx a control-x character

$加双引号($""):实际上与locale设置有关,在C和POSIX下的locale下等同于没带$的双引号
原文:cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored.

第二层:echo接受参数,处理,显示结果
不加-e:按字符显示
加-e: 判断并显示转义(就算你原本打算传进去的就是二个字符,比如'/t')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐