All newlines are removed when saving cat output into a variable
Asked Answered
R

3

33

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?

Rotate answered 2/8, 2013 at 13:40 Comment(0)
J
61

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"
Jest answered 2/8, 2013 at 13:43 Comment(1)
Confusing yet simple. Bash in a nut-shellTraveled
S
1

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

Simpatico answered 15/3, 2018 at 1:4 Comment(2)
why is the first one, the subbash removes newlines, i dont get itEndurant
i found out why, it's because of the IFS, internal field separator, save it, set to blank , and restore itEndurant
B
-6

you can use the redirection "|"

echo | cat test.txt
Bluecoat answered 2/8, 2013 at 13:49 Comment(1)
Doesn't answer the question nor make sense. cat ignores its standard input when passed file name(s) as argument.Jest

© 2022 - 2024 — McMap. All rights reserved.