As per the following example, and as in my recent question In bash, where has the trailing newline char gone?, I want to know "why" it happens
x="$(echo -ne "a\nb\n")" ; echo -n "$x" | xxd -p
# Output is: 610a62
# The trailing newline from the 'echo' command
# has been "deleted" by Command Substitution
I assume there must be some very significant reason for a shell action, namely Command Substitution, to actually delete some data from the command output it is substituting…
but I can't get my head around this one, as it seems to be the antithesis of what it is supposed to do.. ie. to pass the output of a command back into the script process… Holding back one character seems weird to me, but I suppose there is a sensible reason for it… I'm keen to find out what that reason is…
Best Answer
Because the shell was not originally intended to be a full programming language.
It is quite difficult to remove a trailing
\n
from some command output. However, for display purposes, almost all commands end their output with\n
, so… there has to be a simple way to remove it when you want to use it in another command. Automatic removal with the$()
construction was the chosen solution.So, maybe you'll accept this question as an answer:
Can you find a simple way to remove the trailing
\n
if this was not done automatically in the following command?Note that quoting is required to prevent smashing of double spaces that may appear in formatted dates.