How to put content of file into a variable?

For example, I have a simple text file

note:
this a note
a simple note
a very very simple note

when I use this command,

temp=$(cat "note.txt")

then I echo temp, the result is in one line.

echo $temp
note: this a note a simple note a very very simple note

My variable doesn't have newline.
How to make the newline still exist?
And when I echo my variable, it shows same exact form of content.
thanks

# cat file
note:
this a note
a simple note
a very very simple note
# var=$(<file)
# echo "$var"
note:
this a note
a simple note
a very very simple note
1 Like

I don't know it will be as simple as that, because I'm new to bash and I only know cat.
Thanks.:slight_smile:

They are there, but doing echo $var instead of echo "$var" has the side-effect of flattening out all whitespace.

What are you attempting by putting an entire file in a variable? There's probably better and safer ways to do what you want. Many shells have a variable size limit, so this is only guaranteed to work when the file is tiny...

1 Like

Be welcome, you should take Useless Use of Cat Award first.

1 Like

yes, the file's size is small.
It's only contain less then 10 lines, and only have a few words each line.
thanks

Yes, but what are you attempting by putting an entire file in a variable? There's probably better and safer ways to do what you want. As you've already discovered, it can have unintended side-effects.

Yes, but the portable way is

var=$(cat file)

So cat is useful in this case ( $(<file) is bash/ksh93 ).

1 Like