\ n在Heredoc中的变量 [英] \n in variable in heredoc

查看:109
本文介绍了\ n在Heredoc中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以让Bash Heredoc在Heredoc中解释"\ n \"吗?

Is there any way to for a Bash heredoc to interpret '\n\' in a heredoc?

我在循环中有一个迭代生成的字符串,类似

I have an iteratively built string in a loop, something like

for i in word1 word2 word3
do
        TMP_VAR=$i
        ret="$ret\n$TMP_VAR"
done

然后我要在Heredoc中使用创建的字符串:

and then I want to use the created string in a heredoc:

cat <<EOF > myfile
HEADER
==
$ret
==
TRAILER
EOF

但是我想将"\ n"字符解释为换行符,以便输出为

however I would like to interpret the "\n" character as newline, so that the output is

HEADER
==
word1
word2
word3
==
TRAILER

代替

HEADER
==
\nword1\nword2\nword3
==
TRAILER

有可能吗?还是应该以其他方式构建我的初始字符串?

Is it possible? Or should I perhaps build my initial string somehow otherwise?

推荐答案

在bash中,您可以使用$'\n'向字符串中添加换行符:

In bash you can use $'\n' to add a newline to a string:

ret="$ret"$'\n'"$TMP_VAR"

您还可以使用+=附加到字符串:

You can also use += to append to a string:

ret+=$'\n'"$TMP_VAR"

这篇关于\ n在Heredoc中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆