The only way I know is to add an extra line and remove it later. In this way the trailing newlines are preserved since they become embedded, then you can strip the added chars using parameter substitution. This will demonstrate:
Code:
#!/bin/bash
var=$(cat testfile; echo c)
var=${var%??}
echo -n "lines in variable are: "
echo "$var" | wc -l
Here is the output:
Code:
$ cat testfile
line 1
line 2
line 3
line 4
$ wc -l testfile
6 testfile
$ ./test.sh
lines in variable are: 6
The double ?? matches the added "\n" and "c".