Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!';

share|improve this question
up vote 4 down vote accepted

Put this in your .zshrc:

setopt prompt_subst

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.

share|improve this answer
It 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. – Kevin Burke Feb 20 '12 at 2:28
Double 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 – Dominik R Jul 6 at 9:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.