bash - 单引号和反斜杠

・2 分钟阅读

问题


~$ echo $''test'


'test



man bash说:

单引号中的封闭字符保留引号中每个字符的文字值,单引号不能在单引号之间出现,即使在使用反斜杠之前也是如此。

为什么它在echo中工作


回答1:

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)
 b backspace
 e
 E an escape character
 f form feed
 n new line
 r carriage return
 t horizontal tab
 v vertical tab
 backslash
 ' single quote
" double quote
 ? question mark
 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)
 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

这就是为什么!


回答2

单引号'...'与美元单引号$'...'不同,前者不支持任何反斜杠,后者使用的是ANSIC规范。


Tianye profile image