11

I'm adjusting my zsh prompt, based upon the dallas theme and the dstufft theme from oh-my-zsh. I love how dallas has various sections of the prompt contained in variables, which makes it much easier to understand what's going on.

The problem is, these strings are evaluated once for expansion. So when I attempt to use something dynamic, such as the ${PWD/#$HOME/~} of dstufft, then it no longer updates dynamically.

How can I get the best of both worlds? I'd like the prompt broken up into subsections that are evaluated each time the prompt gets written.

4 Answers 4

22

Make sure that the prompt_subst option is turned on. If necessary, add the following line to your ~/.zshrc:

setopt prompt_subst

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:

PS1='${PWD/#$HOME/~}'

The single quotes protect the special characters such as $ from being evaluated when you set the variable.

2
  • 4
    Oh duh! I can't believe I was using double quotes instead of single quotes. Too much Windoze... Commented Jun 13, 2012 at 12:29
  • god, thanks, I've been debugging for hours, and indeed, double quotes...
    – frbl
    Commented Aug 31, 2022 at 21:44
6

In zsh, precmd can do anything (such as setting a variable) before each prompt:

function precmd() {
    current_git_branch=`git rev-parse --abbrev-ref HEAD`
}

http://zsh.sourceforge.net/Doc/Release/Functions.html

This isn't so necessary for the current directory as in the original question, but may be helpful for people who find this question for other cases.

(precmd is zsh-only — in bash, there is $PROMPT_COMMAND.)

1
  • 2
    if you are using oh-my-zsh, do not name your function precmd(), but different, e.g. extra_precmd() and add a precmd_functions+=extra_precmd in your ~/.zshrc somewhere after the having sourced oh-my-zsh.sh
    – village
    Commented Oct 8, 2019 at 19:14
2

Ok,

I just need to escape my $ signs. For example:

${PWD/#$HOME/~}
\${PWD/#\$HOME/~}
1
  • Why isn't this answer upvoted more? Worked for me in zsh, much easier than other suggestions Commented Nov 30, 2020 at 17:19
0

In zsh you should use % escapes for this. For example, instead of ${PWD/#$HOME/~} (as your example), just use %~.

Read zshall(1) and look for SIMPLE PROMPT ESCAPES (it's too long to quote here).

2
  • 1
    I'm following Steve's approach here. You can see the issue that %~ brings up. I'm also running some functions in the prompt. Commented Jun 12, 2012 at 17:57
  • @SpencerRathbun unsetopt cdable_vars would solve the issue of environment variables creeping into %~. Commented Jun 12, 2012 at 22:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .