【问题标题】:Bash echo command not making use of escaped characterBash echo 命令不使用转义字符
【发布时间】:2012-02-06 19:22:59
【问题描述】:

bash echo 命令未使用“\n”和“\t”等转义字符

echo "This is test string\nAnd this is next line"

对于上面的输入,它显示

This is test string\nAnd this is next line

那么如何在下一行打印呢?

【问题讨论】:

  • 不,这是一个shell编程问题。

标签: bash escaping cygwin newline echo


【解决方案1】:

如果你想扩展转义字符,你需要echo -e

$ echo -e "This is test string\nAnd this is next line"
This is test string 
And this is next line

【讨论】:

    【解决方案2】:
    $ echo $'This is test string\nAnd this is next line'
    This is test string
    And this is next line
    

    ANSI-C Quoting

    $'string' 形式的单词被特殊处理。单词扩展为字符串,并按照 ANSI C 标准的规定替换反斜杠转义字符。

    【讨论】:

      【解决方案3】:

      您可以使用echo -e,也可以在脚本开头使用内置的shopt

      shopt -s xpg_echo
      ...
      echo "hello world\n"
      

      【讨论】:

        【解决方案4】:

        echo 命令变化很大——有些实现在其参数中解释转义字符,有些则不解释,除非您添加 -e 选项...有些将打印“-e”作为其输出的一部分如果您尝试将其用作选项。如果您在做任何重要的事情时想要可预测的结果,请改用printf(请注意,您必须明确包含结束换行符):

        printf "This is test string\nAnd this is next line\n"
        

        当 OS X v10.5 附带一个带有内置 echo 的 bash 版本时,我学到了这个教训,这破坏了我在 v10.4 下运行良好的一堆脚本......

        【讨论】:

          猜你喜欢
          • 2011-02-20
          • 2021-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-23
          • 2022-01-04
          • 2013-05-29
          相关资源
          最近更新 更多