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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
output=$(head $file) keeps embedded newlines in the value of output, and trims all trailing newlines.
It’s how you reference the variable that makes the difference.
Placing the variable reference within double quotes, for example:
echo "$output"
prints the embedded newlines, but not the trailing newlines, which were deleted by the command expansion $(...).
This works because the shell interprets only dollar sign, command expansion (back quotes and $(...)), and back slashes within double quotes; the shell does not interpret whitespace (including newlines) as field separators when inside double quotes.
Method 3
To also preserve the exit status:
output=$(head < "$file"; r=$?; echo /; exit "$r")
exit_status=$?
output=${output%/}
Note that using / is safer than x as there are some character sets used by some locales where the encoding of some characters end in the encoding of x (while the encoding of / would generally not be found in other characters as that would make path lookup problematic for instance).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0