Bash – How to Read File Content into a Variable

bashshell

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"?

Best Answer

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

var=$(<file)
Related Question