Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a multiple line value to a bash variable

Tags:

bash

shell

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.

like image 273
molecule Avatar asked Jun 29 '16 04:06

molecule


People also ask

How do I write multiple lines in bash?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you write a multiline string in a shell?

Multiline with \n We can make use of the \n symbol to make sure that whatever string we write has a newline in between them. With this approach we can write as many lines as possible, we just need to write the same number of \n's in the string.

How do you set a variable value in bash?

The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.


1 Answers

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
like image 59
John Kugelman Avatar answered Oct 05 '22 18:10

John Kugelman