Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All newlines are removed when saving cat output into a variable

Tags:

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?

like image 932
MOHAMED Avatar asked Aug 02 '13 13:08

MOHAMED


People also ask

Is variable empty bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What is cat in shell script?

The cat (short for “concatenate“) command is one of the most frequently used commands in Linux/Unix-like operating systems. cat command allows us to create single or multiple files, view content of a file, concatenate files and redirect output in terminal or files.

How do you echo a new line?

There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.


1 Answers

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" 
like image 103
jlliagre Avatar answered Sep 28 '22 10:09

jlliagre