110

我一直在观看 Team Treehouse 的一些视频,他们在使用 Git 时有一个非常漂亮的终端。

例如他们有(类似的东西):

mike@treehouseMac: [/Work/test - feature-branch-name] $ git add .
mike@treehouseMac: [/Work/test - feature-branch-name] $ git commit -m "Some feature."
mike@treehouseMac: [/Work/test - feature-branch-name] $ git checkout master
mike@treehouseMac: [/Work/test - master] $ git status

我的终端如何向我显示我所在分支的一些有用信息,并用颜色区分我想要的数据位?是否有某种我还没有找到的事实上的插件?

我正在使用 Mac OSX 10.8

4

15 回答 15

128

对于在 macOS Catalina 或更高版本(10.15+,包括 Big Sur 11.0)中寻找如何做到这一点的人,已经弃用了 bash 而支持 zsh,这里是我的 .zshrc 文件:

parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF='%f'
COLOR_USR='%F{243}'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{39}'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n@%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '

如果您不喜欢我使用的颜色,请将 243/197/39 值替换为此处定义的颜色代码: https ://misc.flogisoft.com/bash/tip_colors_and_formatting

于 2019-10-14T11:24:26.250 回答
94

简单的方法

在您喜欢的编辑器中打开~/.bash_profile并将以下内容添加到底部。

提示中的 Git 分支。

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

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

将 Git 分支添加到终端提示 (Mac)

于 2013-12-01T05:32:01.687 回答
81

这与插件无关。这是关于 shell 中的提示技巧。

对于 bash 中的一个很酷的设置,请查看dotfiles这个人的项目:

https://github.com/mathiasbynens/dotfiles

要获得花哨的提示,请将 包含.bash_prompt在您的~/.bash_profileor~/.bashrc中。

要获得与您的问题完全相同的提示,请更改export PS1末尾的行,.bash_prompt如下所示:

export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"

.bash*大约一个月前,我最终使用了这个存储库中的所有文件,这对我来说真的很有用。

对于 Git,在.gitconfig.

而且由于您是 mac 用户,因此.osx.

于 2013-06-27T04:02:57.103 回答
25

要扩展现有的出色答案,获得漂亮终端的一种非常简单的方法是使用开源Dotfiles项目。

https://github.com/mathiasbynens/dotfiles


在此处输入图像描述


在 OSX 和 Linux 上安装非常简单。在终端中运行以下命令。

git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh

这将:

  1. Git 克隆存储库。
  2. cd进入文件夹。
  3. 运行安装 bash 脚本。
于 2015-02-07T20:54:13.190 回答
18

我的提示包括:

  • 最后一个命令的退出状态(如果不是 0)
  • root 时的显着变化
  • rsyncuser@host:pathname-复制粘贴的风格
  • Git分支、索引、修改、未跟踪和上游信息
  • 漂亮的颜色

示例: 我的提示在行动的屏幕截图 为此,请将以下内容添加到您的~/.bashrc:

#
# Set the prompt #
#

# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1           # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1           # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1       # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose"     # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR=''          # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe"  # detached HEAD style:
#  contains      relative to newer annotated tag (v1.6.3.2~35)
#  branch        relative to newer tag or branch (master~4)
#  describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
#  default       exactly eatching tag

# Check if we support colours
__colour_enabled() {
    local -i colors=$(tput colors 2>/dev/null)
    [[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1

__set_bash_prompt()
{
    local exit="$?" # Save the exit status of the last command

    # PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
    local PreGitPS1="${debian_chroot:+($debian_chroot)}"
    local PostGitPS1=""

    if [[ $__colourise_prompt ]]; then
        export GIT_PS1_SHOWCOLORHINTS=1

        # Wrap the colour codes between \[ and \], so that
        # bash counts the correct number of characters for line wrapping:
        local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
        local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
        local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
        local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
        local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
        local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
        local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
        local None='\[\e[0m\]' # Return to default colour

        # No username and bright colour if root
        if [[ ${EUID} == 0 ]]; then
            PreGitPS1+="$BRed\h "
        else
            PreGitPS1+="$Red\u@\h$None:"
        fi

        PreGitPS1+="$Blu\w$None"
    else # No colour
        # Sets prompt like: ravi@boxy:~/prj/sample_app
        unset GIT_PS1_SHOWCOLORHINTS
        PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
    fi

    # Now build the part after git's status

    # Highlight non-standard exit codes
    if [[ $exit != 0 ]]; then
        PostGitPS1="$Red[$exit]"
    fi

    # Change colour of prompt if root
    if [[ ${EUID} == 0 ]]; then
        PostGitPS1+="$BRed"'\$ '"$None"
    else
        PostGitPS1+="$Mag"'\$ '"$None"
    fi

    # Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
    __git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'

    # echo '$PS1='"$PS1" # debug    
    # defaut Linux Mint 17.2 user prompt:
    # PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}

# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
于 2016-08-04T04:13:02.907 回答
13

只需按照此链接oh-my-zsh中的说明安装插件。

在此处输入图像描述

它在 macOS 和 Linux 上效果最好。

基本安装

Oh My Zsh 是通过在终端中运行以下命令之一来安装的。您可以通过命令行使用curl或来安装它wget

通过卷曲

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

通过 wget

sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
于 2018-10-25T06:14:51.397 回答
13

在 2019 年,我认为这git branch --show-current是一个比公认答案更好的命令。

$ git branch --show-current
master

(在 2019 年 6 月的 git 2.22 版本中添加)

它运行得更快,因为它不需要遍历所有分支。同样git branch应该避免在命令提示符中使用,因为如果您有许多本地分支,它会减慢您的提示符。

把它放在一个函数中,以便在命令提示符的任何地方使用:

  # This function returns '' in all below cases:
  #   - git not installed or command not found
  #   - not in a git repo
  #   - in a git repo but not on a branch (HEAD detached)
  get_git_current_branch() {
    git branch --show-current 2> /dev/null
  }

更多背景:

$ git version
git version 2.23.0
于 2019-10-23T18:08:25.410 回答
11

对于 Mac Catilina 10.15.5 及更高版本:

添加你的 ~/.zshrc 文件

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

setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '
于 2020-11-16T02:32:26.337 回答
3

安装在系统上的 git 包包含 bash 文件,可帮助您创建信息提示。要创建颜色,您需要在提示符中插入终端转义序列。而且,最后一个要素是在每个命令执行后使用内置变量 PROMPT_COMMAND 更新您的提示。

编辑您的 ~/.bashrc 以包含以下内容,您应该在问题中得到提示,以一些颜色差异为模。

#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh

#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'

#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u@\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""

#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
于 2013-06-27T05:26:35.363 回答
3

对于仍在寻找这个的人,我刚刚安装了 ohmyz https://ohmyz.sh/#install和它显示的分支 在此处输入图像描述

于 2021-01-30T13:08:51.533 回答
2

有许多 PS1 生成器,但ezprompt也有 git 状态(第二个选项卡“状态元素”)。

于 2019-02-28T10:14:20.437 回答
2

在新的 Catalina OS for Mac 中

i) zsh方式。在下面添加以下行.zshrc

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
COLOR_DEF='%f'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{33}'
setopt PROMPT_SUBST
export PROMPT='${COLOR_DIR}%1d${COLOR_DEF}${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '

ii)或者使用旧的bash,你需要改变

   System Preference -> Users & Groups -> Right click user user
     -> Advanced Option -> Login shell -> /bin/bash

编写 .bash_profile 如下并重启系统

parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
export PS1="\W\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "

输出:FolderName BranchName $

于 2021-03-12T05:56:22.553 回答
1

基于 6LYTH3 的回答,我决定发布自己的答案,因为一些改进可能会派上用场:

简单的解决方案

打开~/.bash_profile并添加以下内容

# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
#  \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'

# determines if the git branch you are on is clean or dirty
git_prompt ()
{
  # Is this a git directory?
  if ! git rev-parse --git-dir > /dev/null 2>&1; then
    return 0
  fi
  # Grab working branch name
  git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
  # Clean or dirty branch
  if git diff --quiet 2>/dev/null >&2; then
    git_color="${git_clean_color}"
  else
    git_color="${git_dirty_color}"
  fi
  echo " [$git_color$git_branch${reset_color}]"
}

export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"

这应该:

1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color 
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.

您可以使用此列表自定义颜色

复杂的解决方案

另一种选择是使用 Git Bash Prompt,使用这个. 我在 Mac OS X 上通过 Homebrew 使用了该选项。

git_prompt_list_themes看到主题,但我不喜欢其中任何一个。

git_prompt_color_samples查看可用的颜色。

git_prompt_make_custom_theme [<Name of base theme>]要创建一个新的自定义主题,这应该创建一个 .git-prompt-colors.sh 文件。

subl ~/.git-prompt-colors.sh打开 git-prompt-colors.sh 并自定义:

.git-prompt-colors.sh 文件在我的定制下应该是这样的

    override_git_prompt_colors() {
      GIT_PROMPT_THEME_NAME="Custom"

      # Clean or dirty branch
      if git diff --quiet 2>/dev/null >&2; then
        GIT_PROMPT_BRANCH="${Green}"
      else
        GIT_PROMPT_BRANCH="${Red}"
      fi
    }

    reload_git_prompt_colors "Custom"

希望这会有所帮助,祝您有美好的一天!

于 2019-04-16T21:54:36.653 回答
0

从 Mac OS Catalina .bash_profile 被替换为 .zprofile

第 1 步:创建 .zprofile

touch .zprofile

第2步:

nano .zprofile

在此输入以下行

source ~/.bash_profile

并保存(ctrl+o 返回 ctrl+x)

第三步:重启终端

添加 Git 分支名称 现在您可以在 .bash_profile 中添加以下行

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

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

重新启动您的终端,这将起作用。

注意: 即使您可以将 .bash_profile 重命名为 .zprofile 也可以。

于 2020-05-25T06:39:07.863 回答
0

保持快速,保持简单

把它放在你的~/.bashrc文件中。

git_stuff() {
  git_branch=$(git branch --show-current 2> /dev/null)
  if [[ $git_branch == "" ]];then
    echo -e ""
  elif [[ $git_branch == *"Nocommit"* ]];then
    echo -e "No commits"
  else
    echo -e "$git_branch"
  fi
}
prompt() {
  PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt

然后source ~/.bashrc

在此处输入图像描述

于 2020-08-07T08:02:47.260 回答