Set variables in ZSH precmd and reference them in the prompt
7,074
Put this in your .zshrc
:
setopt prompt_subst
PROMPT='$GREETING'
Then $PROMPT
will undergo parameter expansion (as well as its siblings command substitution and arithmetic expansion) each time it's displayed. Take care to quote anything that gets included from an outside source properly. Also note that the result of the $
expansion will undergo %
expansion (i.e. prompt escape sequences can appear in $GREETING
).
An alternate approach is to reset the PROMPT
variable itself in precmd
, but this makes it harder to customize the prompt in a specific shell instance.
Related videos on Youtube
Author by
Kevin Burke
I build reliable software and design great experiences. I'm available for hire: https://burke.services
Updated on September 18, 2022Comments
-
Kevin Burke over 1 year
Is there a way to set variables in the
precmd
function of zsh and then echo them in the prompt?Something like
function precmd { GREETING='Hi Kevin!'; } PROMPT="$GREETING";
-
Kevin Burke about 12 yearsIt turns out that having double quotes was presenting a problem. Once I changed to single quotes around the PROMPT I got the function to update fine.
-
Abolfazl Najjar almost 8 yearsDouble quotes will expand $GREETING on assignment, i.e. PROMPT will be set to a fixed string. With single quotes, PROMPT will contain the string $GREETING, which will then be reevaluated to the value of $GREETING on every new line, thanks to prompt_subst