Show current Git branch and status in your prompt

轉自:http://www.bramschoenmakers.nl/en/node/624


Those who use git frequently will often execute commands like git status and git branch to check which branch you're on and if there are pending changes.

Fortunately, git offers a Bash script which automatically shows the current state of your repository in your prompt.

To start with, you need to install the bash-completion package. If you're using Arch Linux it's easily done by invoking:

pacman -S bash-completion

Then, you have to modify the start script for Bash such that the new completion scripts will be used. Open~/.bashrc and add the following lines:

# Bash completion
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi

The only thing which is left is to modify the prompt. Add the following line to the file:

export PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[01;33m\]$(__git_ps1)\[\033[01;34m\] \$\[\033[00m\] '

This will show the username and hostname (green) and the current working directory (blue). Only when you're inside a Git repository, it will show the current branch (yellow). In case you already have a fancy pants prompt, it's a matter of incorporating the __git_ps1 function call.

__git_ps1 does not show whether the repository has pending changes. You can enable this by setting the following variable before the PS1 line:

export GIT_PS1_SHOWDIRTYSTATE=1

This shows a asterisk * whenever there are non-committed changes around. It also shows a plus + for changes which are staged but not yet commited (git add). Please note that entering repositories takes considerably longer than before, because it takes a while to check the repository for pending changes. Usually this is only the first time, the disk cache should speed things up in the future.

When you have modified the PS1 variable, you should reload ~/.bashrc:

source ~/.bashrc

And here's the result:

bram@s000000 (master) <span ;="" font-weight:="" bold;"="" style="color: rgb(0, 0, 255);">$


發佈了92 篇原創文章 · 獲贊 28 · 訪問量 72萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章