shell中$后加引号有什么用($"string"和$'string')

Posted liujunjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell中$后加引号有什么用($"string"和$'string')相关的知识,希望对你有一定的参考价值。

有些时候在某些服务管理脚本中看到$"$string"或$"string",经过一些测试,又发现引号外面的$有和没有是一样的。一直也没去找究竟,刚才有人问了我,于是就去翻了下man bash,找到了解释。

(1).如果没有特殊定制bash环境或有特殊需求,$"string"和"string"是完全等价的,使用$""只是为了保证本地化。

以下是man bash关于$""的解释:

 A  double-quoted  string  preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale.  If
       the current locale is C or POSIX, the dollar sign is ignored.  If the string is translated and replaced, the replacement is double-quoted.

(2).还有$后接单引号的$‘string‘,这在bash中被特殊对待:会将某些反斜线序列(如 , ,",‘等)继续转义,而不认为它是字面符号(如果没有$符号,单引号会强制将string翻译为字面符号,包括反斜线)。简单的例子:

[root@localhost ~]# echo a
b
a
b
[root@localhost ~]# echo $a
b
a
b
[root@localhost ~]# echo -e a
b
a
b
[root@localhost ~]# echo -e "a
b"
a
b

以下是man bash里关于$‘的说明:

Words of the form $string are treated specially.  The word expands to string, with backslash-escaped characters replaced as specified  by  the ANSI C standard.  Backslash escape sequences, if present, are decoded as follows:
              a     alert (bell)
                   backspace
              e
              E     an escape character
              f     form feed
              
     new line
              
     carriage return
              	     horizontal tab
              v     vertical tab
              \     backslash
                   single quote
              "     double quote
              
nn   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)
              uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)
              UHHHHHHHH
                     the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)
              cx    a control-x character

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于shell中$后加引号有什么用($"string"和$'string')的主要内容,如果未能解决你的问题,请参考以下文章

shell 中单、双引号问题

shell中,如何替换双引号中内容为某个变量?

VB里面有些运行函数加括号和加引号有啥区别

vbs中wscript.shell对象run调用dos命令的路径问题

Shell脚本

Shell 脚本 - 从变量中删除第一个和最后一个引号 (")