Scenario:
$ cat xxx.txt | od -c
0000000 x \n x \n
0000004
$ value=""
# 1st iteration
$ value+="$(<xxx.txt)" ; echo "$value" | od -c
0000000 x \n x \n
0000004
# 2nd iteration
$ value+="$(<xxx.txt)" ; echo "$value" | od -c
0000000 x \n x x \n x \n
0000007
At the 2nd iteration we see that \n after the 2nd x is lost. Why? How to prevent this?
The expected output is:
0000000 x \n x \n x \n x \n
0000007
echo. Useprintf %s "$value"instead.value="$(<xxx.txt)"thevaluedoesn't contain the last newline character? How to fix?$(...)removes trailing newlines. Sadly there is no fix, command substitution always does that. You can, however, try something like:value+=$(cat xxx.txt; printf x); value=${value%x}(add a trailing character to protect the newline, then remove it afterwards).$(...)removes trailing newlines. TIL. FYI: user Stéphane Chazelas recommends using/rather thanx.