在 Shell 提示符中顯示 Git 分支名稱


| 導語 如果你是用命令行來使用Git的話,當在一個項目中頻繁使用多個分支時,可以使用 git status 命令查詢自己現在正工作在哪個分支下面,不過難免有腦子發昏的時候,忘記自己在哪個分支下面,因而發生誤操作之類的杯具。 那么把分支顯示在 Shell 提示符中無疑方便了很多,再也不需要頻繁的使用 git status 命令了…

 

廢話不多,直接上代碼,放到 ~/.bash_profile 或者 ~/.profile里即可

## Parses out the branch name from .git/HEAD:

find_git_branch () {
  local dir=. head
  until [ "$dir" -ef / ]; do
    if [ -f "$dir/.git/HEAD" ]; then
      head=$(< "$dir/.git/HEAD")
      if [[ $head = ref:\ refs/heads/* ]]; then
        git_branch=" → ${head#*/*/}"
      elif [[ $head != '' ]]; then
        git_branch=" → (detached)"
      else
        git_branch=" → (unknow)"
      fi
      return
    fi
    dir="../$dir"
  done
  git_branch=''
}

PROMPT_COMMAND="find_git_branch; $PROMPT_COMMAND"

# Heree

 
         

black=$'\[\e[1;30m\]'

 
         

red=$'\[\e[1;31m\]'

 
         

green=$'\[\e[1;32m\]'

 
         

yellow=$'\[\e[1;33m\]'

 
         

blue=$'\[\e[1;34m\]'

 
         

magenta=$'\[\e[1;35m\]'

 
         

cyan=$'\[\e[1;36m\]'

 
         

white=$'\[\e[1;37m\]'

 
         

normal=$'\[\e[m\]'

 
         

 

 
         

PS1="$white[$magenta\u$white@$green\h$white:$cyan\w$yellow\$git_branch$white]\$ $normal"

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM