Shengjie Shengjie - 3 months ago 7
Bash Question

How to read the file content into a variable in one go?

In Java, if you know for certain a file is very small, you can use

readBytes()
method to read the content in one go instead of read it line by line or using buffer.

Just wondering in shell script, I know we can do something like:

while read line
do
echo $line
LINE = $line
done < "test.file"
echo $LINE


If my test.file is like:

testline1
testline2
testline3


This only gives me the last line to
$LINE
.
$LINE
contains "testline3".

My question is: How can I read the whole file with multiple lines into one single variable,so I can get
$LINE="testline1\ntestline2\ntestline3"
?

Answer

Process the lines inside the loop instead of after it. If you really need the file in a variable:

var=$(<file)
Comments