I'm having the hardest time trying to get dynamically evaluated command output in my PS1 prompt with zsh on Ubuntu 17.10. Here are a few attempts I've made (I begin in directory /abc, and the prompt is in bold):

$ export PS1="$(pwd) > "
/abc > cd /def
/abc > pwd
/abc > export PS1="\$(pwd) > "
$(pwd) > export PS1='$(pwd) > '
$(pwd) > export PS1='\$(pwd) > '
\$(pwd) > [ragequit]

The first result is the closest, but it looks like the pwd command is being evaluated only once when I define the PS1 variable. Clearly there's something that I don't understand. What can I do to get $(<cmd>) reevaluated every time the command prompt is displayed?

  • 1
    Note that in zsh, a precmd function and setting psvar tends to be easier for doing complicated things than using prompt_subst. And for simple things there's prompt expansion, e.g. %~ for the current directory. Mar 31 '18 at 21:19
  • @Gilles : I understand. I used 'pwd' as a universally recognized command. The real value of the variable is '$(ps1)', where the ps1 command will do whatever I ask it to do - e.g., show the current Git branch. :)
    – Tony
    Apr 5 '18 at 15:04
  • Showing the current git branch is a typical use case of precmd. That's how vcs_info bundled with zsh does it. Apr 5 '18 at 18:41
  • Yeah, but I'm a stickler - I like to see things in a specific way, and I like my config files to be as uncluttered as I can make them. No accounting for taste, hm?
    – Tony
    Apr 6 '18 at 3:23
  • I'm not saying you should use vcs_info. (I don't either.) I'm saying that if you do something similar, you'll have an easier time using precmd and keeping PS1 itself very simple. Apr 6 '18 at 7:00

To get the zsh shell to perform command substitution on the value of PS1, set the PROMPT_SUBST shell option:

PS1='$(pwd) > '

Note that there is no need to export the PS1 variable.

The reason why the PROMPT_SUBST shell option is not set by default is likely that the zsh shell already has rich syntax for prompt expansions.

Your example could, for instance, be replaced by

PS1='%/ > '

For more information about this, see the "EXPANSION OF PROMPT SEQUENCES" section in the zshmisc manual on your system.

When you use

PS1="$(pwd) > "

the value given to the PS1 variable is expanded before the assignment takes place. This is why it does not change when you change directories.

  • Yes indeed. It's odd to me that PROMPT_SUBST isn't the default, but that's my problem. :) Thanks very much.
    – Tony
    Mar 31 '18 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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