Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux. how to preserve lines when setting content of file to environment variable?

I have a file with several lines. When using cat/more/less [file] in the shell,
the content is shown line by line

When doing the following commands:

temp=`cat [file]`
echo $temp

the content is shown in one line.

Is there a way to preserve the line endings when setting to environment variable and then echo it?

Thanks

like image 265
amigal Avatar asked Sep 24 '12 11:09

amigal


People also ask

How do you preserve line breaks when storing command output to a variable?

The Proper Way to Preserve Linebreaks The right way to use a variable is simple: quote the variable. This is because if we quote a variable, the shell will treat it as one single argument to the command, no matter if the variable contains linebreaks or not.

How do I permanently set PATH variable in Linux?

Manipulating your PATH variable To make the change permanent, enter the command PATH=$PATH:/opt/bin into your home directory's . bashrc file. When you do this, you're creating a new PATH variable by appending a directory to the current PATH variable, $PATH . A colon ( : ) separates PATH entries.


1 Answers

Yes:

temp=`cat [file]`
echo "$temp"

The magic is in the quotes around $temp; without them, echo gets these arguments:

echo line1\nline2\nlin3

The shell parsing algorithm will split the command line at white space, so echo sees three arguments. If you quote the variable, echo will see a single argument and the shell parsing won't touch the whitespace between the quotes.

like image 82
Aaron Digulla Avatar answered Nov 15 '22 05:11

Aaron Digulla