且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为bash变量分配多行值

更新时间:2023-02-09 14:23:53

不要缩进行,否则您会得到多余的空格.展开"$ 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