前言

常年使用win做主力机的小伙伴可能没有此需求, 因为在安装程序中, 很多关于git的常用配置都已经在安装过程中配置完毕了。

但对于Linux、和Mac用户而言, git 往往是系统预装或是工具链中附带的, 无需自己手动通过某个安装包来专门安装它, 也因此会出现在使用过程中, 存在一些常用配置为适配的情况——如终端的分支提示、git的命令补全等。 甚至某些简洁镜像中的linux, 连终端字体的提示符颜色都没有配置。

配置

Linux

vim ~/.bashrc

1
2
3
4
5
6
7
8
9
10
11
12
13
# 启用 Git 分支提示
if [ -f ~/.git-prompt/git-prompt.sh ]; then
source ~/.git-prompt/git-prompt.sh
fi

# 带颜色的提示符
export PS1='\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[36m\]$(__git_ps1 " (%s)")\[\e[0m\]\$ '
# export PS1='\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[36m\] WSL \n$(__git_ps1 " (%s)")\[\e[0m\]\$ ' # 这个是我在wsl子系统中为了和 win 父系统做区分设置的。

# Git 命令补全
if [ -f ~/.git-completion/git-completion.bash ]; then
source ~/.git-completion/git-completion.bash
fi

当然, 以上配置中git相关的功能能否正常使用, 主要取决与git相关的配置有没有加载。

  • Git分支提示, 体现在带颜色的提示符相关配置中的$(__git_ps1 " (%s)")这一部分, 而其颜色展示的配置是\[\e[0m\]这一部分(比如对于WSL的专门配置中, WSL的字母颜色也受此影响变为蓝色)。

    • 而这个提示可以展示的前提是以下配置是否添加到了 .bashrc 中, 以及.git-prompt/git-prompt.sh是否加载启用。

      1
      2
      3
      4
      # 启用 Git 分支提示
      if [ -f ~/.git-prompt/git-prompt.sh ]; then
      source ~/.git-prompt/git-prompt.sh
      fi
    • 如未加载启用.git-prompt.sh, 可通过以下步骤进行加载启用。

      • 下载到本地

        1
        2
        mkdir -p ~/.git-prompt
        curl -o ~/.git-prompt/git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh
      • 下载完成后,运行以下命令, 即可激活或者说是加载启用它:

        1
        source ~/.git-prompt/git-prompt.sh
  • Git 命令补全的配置步骤。

    • 在.bashrc中添加以下语句

      1
      2
      3
      4
      # 启用 Git 分支提示
      if [ -f ~/.git-prompt/git-prompt.sh ]; then
      source ~/.git-prompt/git-prompt.sh
      fi
    • 安装 bash-completion(执行如下命令)

      1
      sudo apt install bash-completion
    • 下载 Git 命令补全脚本(执行如下命令)

      1
      2
      mkdir -p ~/.git-completion
      curl -o ~/.git-completion/git-completion.bash https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash

当然, 以上所有配置最终都需要通过.bashrc来体现, 因此我们离不开使得其刷新生效的命令。

1
source ~/.bashrc

Mac

分支提示在Mac上往往是默认配置的, 但 git 命令提示却不是如此, 因此下文会介绍如何在Mac平台配置git 的命令提示功能。

git的命令补全

如果git是通过xcode下载过程中附带安装的, 则需要手动配置补全功能。

对于 Bash 用户

  • 检查 Git 补全脚本:
    • macOS 自带的 Git 通常将补全脚本放在 /Library/Developer/CommandLineTools/usr/share/git-core/git-completion.bash
    • 如果使用 Homebrew 安装的 Git,脚本可能在 /usr/local/etc/bash_completion.d/git-completion.bash

对于zsh用户的相关补全脚本存放路径, 可参考以上。

接下来, 就是在相关配置文件中引用脚本路径就好了。

  • zshrc -> vim ~/.zshrc

    1
    2
    3
    # 加载 Git 补全
    autoload -Uz compinit && compinit
    fpath=(/Library/Developer/CommandLineTools/usr/share/git-core/git-completion.zsh $fpath)
  • bashrc -> vim ~/.bash_profile

    1
    2
    3
    if [ -f /Library/Developer/CommandLineTools/usr/share/git-core/git-completion.bash ]; then 
    . /Library/Developer/CommandLineTools/usr/share/git-core/git-completion.bash
    fi