不同 shell 中带有“echo -e”的转义序列

Bra*_*one 25 shell echo escape-characters

我只是注意到在 Linux 上的 shell 中-e似乎不存在该echo命令的标志。这只是一个混乱的设置还是“正常”?

一些代码为例:

#!/bin/sh
echo -e "\e[3;12r\e[3H"
Run Code Online (Sandbox Code Playgroud)

印刷:

-e \e[3;12r\e[3H
Run Code Online (Sandbox Code Playgroud)

这以前有效!我猜有些stty命令出错了,现在它不再起作用了。有人建议我sh实际上只是bash.

cuo*_*glm 25

因为您使用了sh, not bash,所以echocommand insh没有 option -e。从sh联机帮助页:

echo [-n] args...
            Print the arguments on the standard output, separated by spaces.
            Unless the -n option is present, a newline is output following the
            arguments.
Run Code Online (Sandbox Code Playgroud)

它也没有\e

        If any of the following sequences of characters is encountered
        during output, the sequence is not output.  Instead, the specified
        action is performed:

        \b      A backspace character is output.

        \c      Subsequent output is suppressed.  This is normally used at
                the end of the last argument to suppress the trailing new?
                line that echo would otherwise output.

        \f      Output a form feed.

        \n      Output a newline character.

        \r      Output a carriage return.

        \t      Output a (horizontal) tab character.

        \v      Output a vertical tab.

        \0digits
                Output the character whose value is given by zero to three
                octal digits.  If there are zero digits, a nul character
                is output.

        \\      Output a backslash.

        All other backslash sequences elicit undefined behaviour.
Run Code Online (Sandbox Code Playgroud)

  • 一些 `sh` 实现支持 `echo -e`,在编译时可以告诉 `bash` 不支持 `echo -e`。只是_那个特定的 sh_(可能是 `dash`)不支持 `-e` 而 _那个特定的 `bash`_ 支持。 (5认同)

Chr*_*own 23

-e不是 POSIX(实际上,POSIX echo 通常不接受任何选项,尽管它允许支持-n,请参阅此处),并且/bin/sh在您的系统上似乎是 POSIX shell。-e是某些 shell 中接受的扩展,但您不应依赖它,它不可移植。理想情况下,使用printf或切换到使用具有echo -e.

另请参阅\e下面评论中的警告,应将其替换为\033

printf '\033[3;12r\033[3H'
Run Code Online (Sandbox Code Playgroud)

  • 正如 gnouc 指出的那样,`sh` 也不识别 `\e`。使用`\033` (3认同)