この記事を読んで分かること

Macのターミナル上でGitのブランチ名を表示する方法が分かる。

~/git [master]$ こんな感じで表示される


https://raw.github.com/git/git/master/contrib/completion/git-completion.bashリンク先のコードを git-completion.bash という名前で保存してください。

ホームディレクトリに今作ったファイルを .git-completion.bash というファイル名で保存してください。 ファイル名の先頭にある .(ドット) は隠しファイルにすることを意味しています。

.bash_profile に .git-completion.bash へのパスを通して環境変数 PS1 に値を設定します。私は以下のように設定しました。

~/.bash_profile

# git settings
source ~/.git-completion.bash
GIT_PS1_SHOWDIRTYSTATE=true
PS1='\[\033[32m\]\[\033[00m\]\[\033[34m\]\w\[\033[31m\]$(__git_ps1 " [%s]")\[\033[00m\]\$ '

下のソースコードのコメントと参考サイトを参考にすれば、他の表示パターンも作れると思うので 自分の好きな表示にしてみてください。

PS1 については「bash PS1」などと調べればいろいろ出てきます。 ここで全部説明するのは面倒なので terminal上でgitを使うような人ならこれだけいえば十分ですよね?

git-completion.bash 一部抜粋

# To use these routines:
#
# 1) Copy this file to somewhere (e.g. ~/.git-completion.sh).
# 2) Added the following line to your .bashrc:
# source ~/.git-completion.sh
#
# 3) Consider changing your PS1 to also show the current branch:
# PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
#
# The argument to __git_ps1 will be displayed only if you
# are currently in a git repository. The %s token will be
# the name of the current branch.

参考