Bash - 如何使用 printf 打印多行字符串(带有 '\n')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32371629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:32:00  来源:igfitidea点击:

Bash - How to print multi line strings (with '\n') using printf

linuxbashshellunix

提问by wolfgang

i'm trying to print a multi line strings in printfthis way

我正在尝试以printf这种方式打印多行字符串

printf "hi\n"
printf "next line here\n"

I can't do the following

我不能执行以下操作

text_content="
hi
next line here
"

printf $text_content

Is there any other way?

有没有其他办法?

回答by Reuben L.

Quoting the variable should do the trick. In your example, however, you are getting double newlines.

引用变量应该可以解决问题。但是,在您的示例中,您将获得双换行符。

printf "$text_content"

回答by Andrew

If printf is not necessary, then you may use echo:

如果不需要 printf,则可以使用 echo:

var="one\ntwo"
echo -e $var

回答by tripleee

Here's another variation.

这是另一种变体。

printf '%s\n' 'first line here' 'second line here'

You can add an arbitrary number of arguments; printfwill repeat the format string until all arguments are exhausted.

您可以添加任意数量的参数;printf将重复格式字符串,直到用完所有参数。

printf '%s\n' '#!/bin/sh' \
    'for x; do' \
    '    echo "Welcome to my script!"' \
    'done' >script.sh