Why does command substitution strip trailing newlines, and how do you keep them?
AdvancedConceptVariables, quoting and expansions
Answer
POSIX defines command substitution to remove all trailing newlines, which is usually what you want (x=$(hostname)). When you need exact content (a file that must end in a newline, a PEM block, a value that may end in blank lines), add a sentinel and remove it:
content=$(cat cert.pem; printf x)
content=${content%x}
Also note that command substitution cannot hold NUL bytes; Bash drops them with warning: command substitution: ignored null byte in input. Binary data belongs in files, not variables.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate