When capturing BASH output, apparently BASH deletes trailing blank lines. For example, this:
$ VAR=$(echo -e '\n\n\n\n')
appears to leave VAR with a single newline, as can be seen in any number of ways, e.g. this one:
$ od -c <<< "$VAR"
0000000 \n
0000001
Interestingly, the phenomenon is not confined to capturing output. This somewhat devious experiment:
$ VAR="$(echo -e 'x\nx\nx\nx\n')"
$ VAR="${VAR//x/}"
od -c <<< "$VAR"
0000000 \n \n \n \n
0000004
shows what I want / expect, creating 4 x/newline pairs and deleting the 4 intervening X's. It also verifies that shell variables can contain adjacent newlines, if there was any doubt. However this experiment:
V2="$VAR@$VAR"
od -c <<< "$V2"
0000000 \n \n \n @ \n \n \n \n
0000010
reveals that one newline is lost from the first occurrence of $VAR. NOT what I want or expect. And surprisingly NOT deleting the trailing newlines like the original problem capturing output.
In my application, I need the output to be precisely correct, but I have searched in vain for some way to turn off this "helpful" feature (or is it a bug?). I have not been able to play with this and find a workaround either, other than by using a kludge, e.g. capturing output that always includes an added line of non-blank text, such as:
VAR=$(some program ; echo "EOF")
This behavior is on a Debian 10 system with BASH 5.0.3, but I have also verified the same behavior on BASH 4.4.12. My guess is that it may have been around a long time.
I wonder if anyone knows how to get BASH to keep newlines in variables with the same integrity that it does every other character?