在 zsh shell 上的提示符下显示当前分支

Pet*_*dis 3 macos shell

我正在尝试在 Big Sur 上的提示符下显示 git 分支。所以我创建了一个脚本文件来为每个新会话运行.zshrc

# Git branch in prompt.
parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ [\1]/'
}
export PS1="\u@\h \W\[\033[01;33m\]\$(parse_git_branch)\[\033[00m\] $ "
Run Code Online (Sandbox Code Playgroud)

上面的方法不起作用,它实际上显示字符串而不是其输出。

\u@\h \W\[\033[01;33m\]$(parse_git_branch)\[\033[00m\] $
Run Code Online (Sandbox Code Playgroud)

如何在 zsh shell 的提示符中显示当前分支?

Jav*_*olo 5

我假设你想显示这样的东西[username@computername directory](branch)

下面的代码应该为 Zsh 执行此操作,这比在bash. 对此有多种解决方案,如果您有兴趣,可以在此处找到更多信息。

将以下内容添加到您的 .zshrc 或 .zsh_profile

# Load version control information
autoload -Uz vcs_info
precmd() { vcs_info }

# Format the vcs_info_msg_0_ variable
zstyle ':vcs_info:git:*' formats '%b'

# Set up the prompt (with git branch name)
setopt PROMPT_SUBST

PROMPT='[%n@%m %1~]%F{green}(${vcs_info_msg_0_})%F{white}$ '
Run Code Online (Sandbox Code Playgroud)

了解 和 之间的差异将是有益的,bash因为zsh您不能互换使用在线找到的解决方案。