【问题标题】:How can I display the current branch and folder path in terminal?如何在终端中显示当前分支和文件夹路径?
【发布时间】:2013-06-24 09:16:56
【问题描述】:

我一直在观看 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

【问题讨论】:

    标签: macos git terminal git-branch


    【解决方案1】:

    对于在 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

    【讨论】:

    • 完美运行,我很感激。
    • 这很好用——谢谢你写这篇文章。羞耻 zsh 不能像其他 bashes 一样运行!
    • 在哪里可以找到 .zshrc 文件?我在我的主目录或 /Users/myusername 上,但如果我运行 ls -lah,我在列表中看不到它 - 也没有 .bashrc 或 .bash_profile。我能看到的唯一相关文件是 .bash_history 和 .zsh_history
    • @ltdev 该文件默认不一定存在,因为它是可选文件。如果它不存在,那么您需要使用命令touch .zshrc(在您的主目录中)创建该文件
    • @Merowinger 出于某种原因,此页面上的解决方案都不适合我(big sur),但这个较旧的解决方案可以:github.com/olivierverdier/zsh-git-prompt
    【解决方案2】:

    简单的方法

    在你喜欢的编辑器中打开~/.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\] $ "
    

    Add Git Branch To Terminal Prompt (Mac)

    【讨论】:

    • 我喜欢在末尾的 $ 符号前加一个 \n,以便将我的提示放在下一行。
    • 完全自定义花了 5 分钟!这是颜色:misc.flogisoft.com/bash/tip_colors_and_formatting
    • 在最新版本的 mac bash_profile 中并非每次都加载。因此,最好在.zshrc 上进行设置。谢谢
    【解决方案3】:

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

    要在 bash 中设置一个很酷的设置,请查看此人的 dotfiles 项目:

    https://github.com/mathiasbynens/dotfiles

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

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

    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 中还有更多好东西。

    【讨论】:

    • 在此之后我得到:bash: parse_git_branch: command not found
    • @SharikovVladislav 对此有何更新?我们如何解决parse_git_branch: command not found
    • 要修复parse_git_branch 错误,您必须将函数定义为:parse_git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/' }
    • parse_git_branch 大概是从这里复制的:gist.github.com/joseluisq/1e96c54fa4e1e5647940
    【解决方案4】:

    要扩展现有的出色答案,获得漂亮终端的一种非常简单的方法是使用开源 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 脚本。

    【讨论】:

    • 关于如何扭转这种情况的任何想法??
    • 需要注意的是,这个单行可能会覆盖很多文件,所以要小心
    • 警告:除非您知道这意味着什么,否则不要盲目使用我的设置。使用风险自负!
    • 这会添加大量配置,甚至不需要备份它写入的文件。
    • 这是一个极端的举动,会对你的所有设置造成严重破坏。
    【解决方案5】:

    我的提示包括:

    • 最后一个命令的退出状态(如果不是 0)
    • root 后的显着变化
    • rsync-style user@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
    

    【讨论】:

    • 对于信息丰富的提示来说,这是非常干净的代码。我花了很多时间在我的提示上工作并爬出陷阱,基本上达到了你在这里所拥有的东西。如果在提示符下处理自定义的、彩色的 git 状态,我强烈建议从这段代码开始。
    • 向你推荐 Tom,这是迄今为止我遇到的最干净且易于修改的解决方案。 @wisbucky 绝对正确
    【解决方案6】:

    只需按照this link 中的说明安装oh-my-zsh 插件即可。

    它在 macOS 和 Linux 上运行得最好。

    基本安装

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

    通过卷曲

    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 -)"
    

    【讨论】:

      【解决方案7】:

      在 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 年的优秀答案。接受和最受欢迎的答案显示了他们的年龄。
      • 最小而完美的答案:D
      【解决方案8】:

      对于 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 '
      

      【讨论】:

      • 谢谢,它对我有用!有没有办法隐藏完整路径并只显示当前文件夹?
      • @bibsbarreto 将 PROMPT 从 %~ 更改为 %. 所以最终是:export PROMPT='%F{grey}%n%f %F{cyan}%.%f %F{green}$(parse_git_branch)%f %F{normal}$%f 参考:zsh.sourceforge.io/Doc/Release/…
      【解决方案9】:

      安装在您系统上的 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
      

      【讨论】:

        【解决方案10】:

        对于仍在寻找这个的人,我刚刚安装了 ohmyz https://ohmyz.sh/#install 和它显示的分支

        【讨论】:

        • 这就是我需要的!谢谢
        【解决方案11】:

        在新的 Mac 版 Catalina 操作系统中

        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 $

        【讨论】:

          【解决方案12】:

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

          【讨论】:

            【解决方案13】:

            根据 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.
            

            你可以用这个list自定义颜色

            复杂的解决方案

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

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

            git_prompt_color_samples 查看可用颜色。

            git_prompt_make_custom_theme [&lt;Name of base theme&gt;] 创建一个新的自定义主题,这应该创建一个 .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"
            

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

            【讨论】:

            • 感谢脚本,这在我的 ubuntu 19.10 中运行良好。
            • 很高兴能帮上忙!我使用的是 Mac 儿子,这意味着它适用于 Mac 和一些 Ubuntus
            【解决方案14】:

            来自 Mac OS Catalina .bash_profile 替换为 .zprofile

            第 1 步: 创建一个 .zprofile

            touch .zprofile
            

            第 2 步:

            nano .zprofile
            

            在下面一行输入

            source ~/.bash_profile
            

            然后保存(ctrl+o 返回 ctrl+x)

            第 3 步: 重启你的终端

            添加 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 也可以。

            【讨论】:

            • 下一条消息在更改后出现并且不起作用 -> zsh compinit: insecure directories, run compaudit for list. Ignore insecure directories and continue [y] or abort compinit [n]?
            • 在哪里可以找到 .zprofile 文件?我在我的主目录或 /Users/myusername 上,但如果我运行 ls -lah,我在列表中看不到它 - 也没有 .bashrc 或 .bash_profile 或 .zshrc。我能看到的唯一相关文件是 .bash_history 和 .zsh_history
            【解决方案15】:

            保持速度,保持简单

            将其放入您的 ~/.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

            【讨论】:

              猜你喜欢
              • 2019-02-10
              • 1970-01-01
              • 1970-01-01
              • 2013-07-21
              • 2021-02-28
              • 1970-01-01
              • 1970-01-01
              • 2020-03-19
              • 1970-01-01
              相关资源
              最近更新 更多