Hi I know that you set the prompt variable to edit the prompt like this
export PROMPT="This is the date %d"
How do you execute a command and print the result everytime when prompt loads.
Hi I know that you set the prompt variable to edit the prompt like this
export PROMPT="This is the date %d"
How do you execute a command and print the result everytime when prompt loads.
There are actually two (main) ways to achieve this:
Use command substitution to run a command as part of the prompt
promptsubst
has to be enabled, elsezsh
will not do any paremeter expansions, arithmetic expansions or command substitutions.Also, the prompt text needs to be quoted in such a way that the expansions are not made when setting
PROMPT
. So either put it in single quotes or, if you have/want to use double quotes, prepend$
with a\
to quote them separately where necessary:This will expand
$(another_command)
when settingPROMPT
(so it is run only once and its result than substituted permanently) and$(a_command)
every time the prompt is shown.Make use of the
precmd
function (or hook) and thepsvar
array:precmd
function is run just before the prompt is printed. You can also set a list of functions to run in theprecmd_functions
array.add-zsh-hook
provides an easy way to add functions to that array.%Nv
in the prompt is replaced by the N-th element of thepsvar
array. IfN
is left out (%v
)N==1
is assumed (this is also true for other prompt token that take numeric arguments)On first glance the second method may look far more complicated then just using
promptsubst
. But this is only the case for very simple substitutions. Usingprecmd
allows for using more complex functions without making the definition ofPROMPT
unreadable due to cramming several lines of code inside a$( )
.You can also combine both approaches and forego the use of
psvar
in some or all cases: