问题
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"
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.
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.
回答1:
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
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"
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
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
回答2:
When you initialize FOO you should use line breaks: \n.
FOO="This is line 1\nThis is line 2\nThis is line 3"
Then use echo -e to output FOO.
It is important to note that
\ninside"..."is NOT a line break, but literal\, followed by literaln. It is only when interpreted byecho -ethat this literal sequence is converted to a newline character. — wise words from mklement0
#!/bin/bash
FOO="This is line 1\nThis is line 2\nThis is line 3"
echo -e $FOO
Output:
This is line 1
This is line 2
This is line 3
回答3:
You could also store the lines to a variable using read lines:
$ read -r -d '' FOO << EOF
This is line 1
This is line 2
This is line 3
EOF
To see the newline on printing use quotes around the variable: (echo "$FOO" not echo $FOO)
$ echo "$FOO"
This is line 1
This is line 2
This is line 3
来源:https://stackoverflow.com/questions/38090646/how-to-assign-a-multiple-line-value-to-a-bash-variable