首页 > 解决方案 > macOS终端配置问题,设置颜色和git分支信息

问题描述

我在 macOS Big Sur 11.1 中的终端显示配置有问题我希望它看起来像 CMDer 编辑器中的 windows 终端。可以在下图中使用

(img) 我想要这样的东西

我非常习惯这种终端的外观,所以我开始寻找解决方案。我发现,我需要配置 .zshrc 文件来更改颜色并在需要时添加 git 信息。

我找到了需要在 .zshrc 文件中设置的代码:

parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}

COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;44m'
COLOR_DIR=$'\e[38;5;106m'
COLOR_GIT=$'\e[38;5;208m'
NEWLINE=$'\n'

setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DEF}in ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}Ⲗ '

它适用于颜色。我无法使 parse_git_branch 函数工作。我不知道这里发生了什么。在其他帖子中,有信息表明该方法有效。

(img)目前,我有这样的东西。没有 git 分支信息

标签: bashmacosterminalconfigurationzsh

解决方案


干得好:

parse_git_branch() {
  local branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

  # If the branch is non-zero
  if [[ -n $branch ]]; then

    # -n: Don't print a newline at the end.
    # -P: Substitute prompt expansions.
    # %F{y}: Foreground color yellow
    print -nP - "%F{y}($branch"

    local tracking=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null)
    [[ -n $tracking ]] &&
      print -nP - " -> $tracking"
    print - ')'
  fi
}

setopt promptsubst

# %F{g}: Foreground color green
# %~: pwd with named dir substitution
# %f: Default foreground color
export PS1='%F{g}%~ $(parse_git_branch)
%fⲖ '

参考:


推荐阅读