23

I have the following file

linux$ cat test.txt
toto
titi
tete
tata

Saving the cat output into a variable will discard the newlines

linux$ msgs=`cat test.txt`
linux$ echo $msgs
toto titi tete tata

How to keep the output containing the newlines in the variables?

jlliagre
  • 27,018
  • 6
  • 57
  • 68
MOHAMED
  • 35,883
  • 48
  • 140
  • 238

3 Answers3

44

The shell is splitting the msgs variable so echo get multiple parameters. You need to quote your variable to prevent this to happen:

echo "$msgs"
jlliagre
  • 27,018
  • 6
  • 57
  • 68
0

I had this:

echo $(cat myfile.sh) >> destination.sh

that was causing the problem, so I changed it to:

cat myfile.sh >> destination.sh

and that worked, lulz

Alexander Mills
  • 1
  • 80
  • 344
  • 642
-6

you can use the redirection "|"

echo | cat test.txt
alexis
  • 569
  • 5
  • 10
  • 2
    Doesn't answer the question nor make sense. `cat` ignores its standard input when passed file name(s) as argument. – jlliagre Aug 02 '13 at 14:25