1

I am trying to print the content of a variable in a bash script. I need all the line breaks just as in the string, especially in the end of it.

Given an example file:

$ touch test.txt
$ echo "A" >> test.txt 
$ echo "B" >> test.txt 
$ echo "C" >> test.txt 
$ echo "" >> test.txt 
$ echo "" >> test.txt 

cat test.txt will print:

$ cat test.txt 
A
B
C


$

(with two additional line breaks. Added $ for formatting).

However, If I run echo, it returns

$ var=$(cat test.txt)
$ echo $var
A B C
$ echo "$var"
A
B
C

Adding quotation marks only prints line breaks in the middle of the string, not at the end.

How can I print the trailing line breaks?

exception1
  • 1,239
  • 8
  • 17
  • 1
    Command substitution will remove trailing newlines, but you can use `read` like this instead: `IFS= read -rd '' var < test.txt`. – randomir Aug 20 '17 at 21:46

0 Answers0