Interview Prep/Shell Scripting/Variables, quoting and expansions

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions