Bash Shell Newlines – How to Preserve Newline Character in Command Output

bashcommand-substitutionnewlinesshell

As a simple example, I have a bunch of source code files. I want to store the "head" command output to a variable for all these files.

I tried:

output=$(head $file)

but what happened is that this automatically trimmed all \n characters when storing the output to a variable.

How do I store the command output as is without removing \n characters?

Best Answer

It is a known flaw of "command expansion" $(...) or `...` that the last newline is trimmed.

If that is your case:

$ output="$(head -- "$file"; echo x)"     ### capture the text with an x added.
$ output="${output%?}"                    ### remove the last character (the x).

Will correct the value of output.

Related Question