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?
> echo The current date is "$(date)", have a good day!
Note that quoting is required to prevent smashing of double spaces that may appear in formatted dates.
Final newlines are removed from command substitutions. Even zsh doesn't provide an option to avoid this. So if you want to preserve final newlines, you need to arrange for them not to be final newlines.
The easiest way to do this is to print an extra character (other than a newline) after the data that you want to obtain exactly, and remove that final extra character from the result of the command substitution. You can optionally put a newline after that extra character, it'll be removed anyway.
In zsh, you can combine the command substitution with the string manipulation to remove the extra character.
my_info='${$(my_info; echo .)%.}'
PROMPT="${my_info}My awesome prompt $>"
In your scenario, take care that my_info
is not the output of the command, it's a shell snippet to get the output, which will be evaluated when the prompt is expanded. PROMPT=${my_info%x}…
didn't work because that tries to remove a final x
from the value of the my_info
variable, but it ends with )
.
In other shells, this needs to be done in two steps:
output=$(my_info; echo .)
output=${output%.}
In bash, you wouldn't be able to call my_info
directly from PS1
; instead you'd need to call it from PROMPT_COMMAND
.
PROMPT_COMMAND='my_info=$(my_info; echo .)'
PS1='${my_info%.}…'
Best Answer
This should work:
The script always prints previous line instead of current, and the last line is treated differently.
What it does in more detail:
NR>1{print PREV}
Print previous line (except the first time).{PREV=$0}
Stores current line inPREV
variable.END{printf("%s",$0)}
Finally, print last line withtout line break.Also note this would remove at most one empty line at the end (no support for removing
"one\ntwo\n\n\n"
).