All new lines are deleted when saving the cat output to a variable

I have the following file

linux$ cat test.txt toto titi tete tata 

Saving cat output to a variable will discard newlines

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

How to save output containing newlines in variables?

+6
source share
3 answers

The shell shares the msgs variable, so echo gets a few parameters. You must specify your variable to prevent this from happening:

 echo "$msgs" 
+20
source

I had this:

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

which caused the problem, so I changed it to:

 cat myfile.sh >> destination.sh 

and it worked, lulz

0
source

you can use the redirect "|"

 echo | cat test.txt 
-6
source

Source: https://habr.com/ru/post/950908/


All Articles