如何修改我的 zsh 终端提示以显示当前工作目录和当前 git 分支(如果适用)?

How can I modify my zsh terminal prompt to show the current working directory and current git branch (if applicable)?

我是 运行 macOS Big Sur v11.2。我希望我的 zsh 终端提示看起来像这样:

/directoryName/ (gitbranch) $

谢谢!

一种方法是使用 zsh precmd 通过内置的 vcs_info 构建提示。尝试将此添加到 ~/.zshrc 并重新启动终端会话:

my_precmd() {
  vcs_info
  psvar[1]=$vcs_info_msg_0_
  if [[ -n ${psvar[1]} ]]; then
    psvar[1]=" (${psvar[1]})"
  fi
}

autoload -Uz vcs_info
zstyle ':vcs_info:git:*' formats '%b'
autoload -Uz add-zsh-hook
add-zsh-hook precmd my_precmd
PROMPT='%d/%1v $ '

关于这些作品的一些注释在这里: Different zsh terminal prompt when outside git directory