gpt4 book ai didi

bash - 如何将多行值分配给 bash 变量

转载 作者:行者123 更新时间:2023-11-29 08:48:06 25 4
gpt4 key购买 nike

我有一个变量 FOO 需要分配一个多行的值。像这样,

FOO="This is line 1
This is line 2
This is line 3"

所以当我打印 FOO 的值时,它应该给出以下输出。

echo $FOO
output:
This is line 1
This is line 2
This is line 3

此外,行数将动态决定,因为我将使用循环对其进行初始化。

另一个问题中主要使用read -d 显示的答案不适合我,因为我正在进行密集的字符串操作,代码格式也很重要。

最佳答案

不要缩进行,否则会出现额外的空格。展开 "$FOO" 时使用引号以确保保留换行符。

$ 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 转义序列。它们在 $'...' 字符串中被解释。

$ FOO=$'This is line 1\nThis is line 2\nThis is line 3'
$ echo "$FOO"

第三种方法是存储字符\n,然后让echo -e 解释转义序列。这是一个微妙的区别。重要的是 \n 不会在常规引号内进行解释。

$ 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 打印原始字符串而不解释任何内容,您可以看到我所做的区别。

$ echo "$FOO"
This is line 1\nThis is line 2\nThis is line 3

关于bash - 如何将多行值分配给 bash 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38090646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com