Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and echo multiple lines elegantly in bash? [duplicate]

Tags:

I'm trying to capture a block of text into a variable, with newlines maintained, then echo it.

However, the newlines don't seemed to be maintained when I am either capturing the text or displaying it.

Any ideas regarding how I can accomplish this?

Example:

#!/bin/bash  read -d '' my_var <<"BLOCK" this is a test BLOCK  echo $my_var 

Output:

this is a test

Desired output:

this

is

a

test

like image 727
EmpireJones Avatar asked May 02 '10 06:05

EmpireJones


People also ask

How do I echo 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.

How do I store a multiline string in bash?

Bash Escape Characters For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary. Executing the above script prints the strings in a new line where the \n character exists.

How can you create a multiline echo or assignment?

echo $var ; ?> Using concatenation assignment operator: We can use the concatenation assignment operator . = to concatenate two strings and the PHP_EOL to mark the end of the line.

What is echo $$ in bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.


1 Answers

echo "$my_var" 
like image 178
kennytm Avatar answered Nov 09 '22 03:11

kennytm