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.
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.
$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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With