Bash echo 命令不使用转义字符

发布于 2024-12-26 11:27:10 字数 235 浏览 2 评论 0原文

bash echo 命令不使用转义字符,例如“\n”和“\t”

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

对于它显示的上述输入

This is test string\nAnd this is next line

那么如何在下一行打印?

The bash echo command isn't using the escaped characters like "\n" and "\t"

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

For the above input it displays

This is test string\nAnd this is next line

So how do I print on the next line?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

来世叙缘 2025-01-02 11:27:10

如果您希望扩展转义字符,则需要 echo -e

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

You need echo -e if you want escaped characters to be expanded:

$ echo -e "This is test string\nAnd this is next line"
This is test string 
And this is next line
花桑 2025-01-02 11:27:10
$ echo 

ANSI-C 引用

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

This is test string\nAnd this is next line' This is test string And this is next line

ANSI-C 引用

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

$ echo 

ANSI-C Quoting

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.

This is test string\nAnd this is next line' This is test string And this is next line

ANSI-C Quoting

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.

不奢求什么 2025-01-02 11:27:10

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

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

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

The echo command varies quite a bit -- some implementations interpret escape characters in their arguments, some don't unless you add the -e option... some will print "-e" as part of their output if you try to use it as an option. If you want predictable results when doing anything nontrivial, use printf instead (note that you must explicitly include the ending newline):

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

I learned this lesson the hard way, when OS X v10.5 came with a version of bash with a builtin echo that broke a bunch of my scripts that'd worked just fine under v10.4...

沒落の蓅哖 2025-01-02 11:27:10

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

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

You can use echo -e or you can use the shopt built-in thusly at the beginning of your script:

shopt -s xpg_echo
...
echo "hello world\n"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文