有人能帮助我理解的行为echo
吗?我在 Ubuntu 中尝试以下命令:
$ echo -e \xaa
xaa
$ echo -e "\xaa"
▒
$
如您所见,使用双引号时,在打印十六进制时,输出是一些垃圾。我知道-e
解释\n
为换行符和其他序列很有用。我只是想了解带-e
选项的 echo 如何处理十六进制。
答案1
如果没有引号,\x
则 shell 会将其解析为x
:
$ printf "%s\n" echo -e \xaa
echo
-e
xaa
$ printf "%s\n" echo -e "\xaa"
echo
-e
\xaa
看man bash
, 部分QUOTING
:
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).
你的grep
说法具有误导性:
$ man echo | grep -o \xHH
xHH
grep -o
准确打印匹配的字符,表明grep
从未收到\
。
除非您运行/bin/echo
或env echo
,否则将运行 shell 的内置命令echo
。因此,如果您想查看文档,请运行help echo
,或者查看man bash
。man echo
适用于/bin/echo
:
$ echo --help
--help
$ env echo --help
Usage: echo [SHORT-OPTION]... [STRING]...
or: echo LONG-OPTION
Echo the STRING(s) to standard output.
-n do not output the trailing newline
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes (default)
--help display this help and exit
--version output version information and exit
If -e is in effect, the following sequences are recognised:
\\ backslash
...
请参阅man bash
第节SHELL BUITLIN COMMANDS
:
echo interprets the following escape sequences:
\a alert (bell)
\b backspace
\c suppress further output
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0nnn the eight-bit character whose value is the octal value
nnn (zero to three octal digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)