Mot*_*001 6 bash echo escape-characters
我一直认为 bash 在不带或带双引号的情况下对反斜杠的处理方式相同,但我错了:
[user@linux ~]$ echo "foo \ "
foo \
[user@linux ~]$ echo foo \ # Space after \
foo
Run Code Online (Sandbox Code Playgroud)
所以我认为在使用双引号时总是会打印反斜杠,但是:
[user@linux ~]$ echo "foo \" "
foo "
[user@linux ~]$ echo "foo \\ "
foo \
Run Code Online (Sandbox Code Playgroud)
为什么显示第一行代码中的反斜杠?
Eli*_*gan 10
反斜杠仅在后跟以下字符之一时保留其特殊含义:'
$
'、'`
'、'"
'、'\
' 或newline
。在双引号内,后跟这些字符之一的反斜杠将被删除。没有特殊含义的字符前面的反斜杠保持不变。双引号可以通过在双引号前面加上反斜杠来引用。如果启用,将执行历史扩展,除非!
使用反斜杠转义双引号中出现的 ' '。'!
'前面的反斜杠不会被删除。
因此\
,双引号中的处理方式与\
单引号中和\
外引号中的处理方式不同。它按字面处理,除非它可以使字符按字面处理,否则在双引号中可能具有特殊含义。
请注意,像\'
, \?
, and这样的序列按\*
字面意思处理,并且不会删除反斜杠,因为'
,?
和*
用双引号括起来时已经没有特殊含义。
反斜杠根据上下文有不同的解释:
在双引号内(您的第一个示例):
The backslash retains its special meaning only when followed
by one of the following characters: $, `, ", \, or <newline>.
Run Code Online (Sandbox Code Playgroud)没有引号(你的第二个例子):
A non-quoted backslash (\) is the escape character. It
preserves the literal value of the next character that
follows, with the exception of <newline>. If a \<newline>
pair appears, and the backslash is not itself quoted, the
\<newline> is treated as a line continuation (that is, it is
removed from the input stream and effectively ignored).
Run Code Online (Sandbox Code Playgroud)使用结构$'....'
,在那里你可以报价内使用标准的退格字符,几乎为C.例如\n
,\t
等等。
使用反引号:
When the old-style backquote form of substitution is used,
backslash retains its literal meaning except when followed by
$, `, or \.
Run Code Online (Sandbox Code Playgroud)引用来源:bash 手册