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
Make sure that the
prompt_subst
option is turned on. If necessary, add the following line to your~/.zshrc
:This tells zsh to reevaluate the prompt string each time it's displaying a prompt. Then, make sure you are assigning
PS1
(or some other variable that is used by the prompt theme) as desired:The single quotes protect the special characters such as
$
from being evaluated when you set the variable.