如何为bash变量分配多行值 [英] How to assign a multiple line value to a bash variable
问题描述
我有一个变量 FOO
,需要为它分配一个多行值.像这样的东西
I have a variable FOO
with me that needs to be assigned with a value that will be multiple lines. Something like this,
FOO="This is line 1
This is line 2
This is line 3"
因此,当我打印 FOO
的值时,应提供以下输出.
So when I print the value of FOO
it should give the following output.
echo $FOO
output:
This is line 1
This is line 2
This is line 3
此外,行数将动态确定,因为我将使用循环对其进行初始化.
Furthermore, the number of lines will be decided dynamically as I will initialize it using a loop.
在另一个问题中主要使用 read -d
显示的答案不适合我,因为我正在执行大量的字符串操作,并且代码格式也很重要.
The answers that have been shown in the other question using mainly read -d
is not suitable for me as I am doing intensive string operations and the code format is also important.
推荐答案
不要缩进行,否则您会得到多余的空格.展开"$ FOO"
时,请使用引号,以确保保留换行符.
Don't indent the lines or you'll get extra spaces. Use quotes when you expand "$FOO"
to ensure the newlines are preserved.
$ FOO="This is line 1
This is line 2
This is line 3"
$ echo "$FOO"
This is line 1
This is line 2
This is line 3
另一种方法是使用 \ n
转义序列.它们在 $'...'
字符串内解释.
Another way is to use \n
escape sequences. They're interpreted inside of $'...'
strings.
$ FOO=$'This is line 1\nThis is line 2\nThis is line 3'
$ echo "$FOO"
第三种方法是存储字符 \
和 n
,然后让 echo -e
解释转义序列.这是一个微妙的区别.重要的是, \ n
不会在常规引号内进行解释.
A third way is to store the characters \
and n
, and then have echo -e
interpret the escape sequences. It's a subtle difference. The important part is that \n
isn't interpreted inside of regular quotes.
$ FOO='This is line 1\nThis is line 2\nThis is line 3'
$ echo -e "$FOO"
This is line 1
This is line 2
This is line 3
如果删除 -e
选项并让 echo
打印原始字符串而不解释任何内容,则可以看到我的区别.
You can see the distinction I'm making if you remove the -e
option and have echo
print the raw string without interpreting anything.
$ echo "$FOO"
This is line 1\nThis is line 2\nThis is line 3
这篇关于如何为bash变量分配多行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!