28

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

Community
  • 1
  • 1
EmpireJones
  • 2,936
  • 4
  • 29
  • 43

1 Answers1

59

You need to add " quotes around your variable.

echo "$my_var"
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    Would still like to see related documentation if any1 has it? Thanks for the answer nonetheless – Sam Stoelinga Nov 05 '14 at 09:55
  • 4
    @SamStoelinga: from 'info echo': [`echo' writes each given STRING to standard output, with a space between each and a newline after the last one.] Without quotes, echo interprets the lines in the input as separate strings, and prints them out, separated by spaces. With quotes, echo prints the input as one string (which contains many lines). – Roman Kogan Aug 05 '16 at 23:35