转自:http://zurb.com/forrst/posts/Displaying_the_Git_branch_in_your_BASH_prompt-iLv
把下面代码放到~/.bash_profile 中
function 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='(unknown)'
fi
return
fi
dir="../$dir"
done
git_branch=''
}
PROMPT_COMMAND="find_git_branch; $PROMPT_COMMAND"
red=$'\e[31m'
normal_colours=$'\e[m'
PS1="\[$red\]\$git_branch\[$normal_colours\] \w \$ "